This is an introduction to keyboard shortcuts in Bash and Readline. To see the list of shortcuts, skip to the summary.

Introduction

We all make mistakes when running commands in a terminal. Fixing these mistakes can be tedious. Do you ever find yourself pressing the arrow keys repeatedly to move the cursor?

$ ls secrets/
ls: cannot open directory 'secrets/': Permission denied

# <Up> <Left> <Left> <Left> <Left> <Left> <Left> <Left> […]

$ sudo ls secrets/

Ouch. That’s a lot of key presses.

Fortunately, it doesn’t have to be this way. Bash uses the Readline library, which provides a number of keyboard shortcuts to move the cursor and edit text.

Back to the beginning

Press Ctrl-A to move the cursor to the beginning of the line.

$ ls secrets/
ls: cannot open directory 'secrets/': Permission denied

# <Up> <Ctrl-A> sudo

$ sudo ls secrets/

Press Ctrl-E to return to the end of the line.

Moving between words

Press Alt-B to move the cursor backwards by one word.

Press Alt-F to move forwards by one word.

$ git commit 'Update README.md'
error: pathspec 'Update README.md' did not match any file(s) known to git

# <Up> <Ctrl-A> <Alt-F> <Alt-F> -m

$ git commit -m 'Update README.md'

These shortcuts might not work if the Alt key has been reserved for other uses, such as typing accented characters. However, there is another way: press and release the Esc key, then press B or F. This works for all Readline shortcuts that use the Alt key.

Deleting words

Press Ctrl-W to delete the previous word (to the left of the cursor).

$ git add start.sh stop.sh
fatal: pathspec 'stop.sh' did not match any files

# <Up> <Ctrl-W>

$ git add start.sh

Press Alt-D to delete the next word (to the right of the cursor).

Undo

Yes, you can even undo. Press Ctrl-_ (that’s the hyphen/underscore key).

For example, if you deleted a word with Ctrl-W, press Ctrl-_ to bring it back.

The undo history only applies to the current line.

Summary

And that’s it. Here’s a cheat sheet:

Shortcut Effect
Ctrl-A Move to the beginning of the line.
Ctrl-E Move to the end of the line.
Alt-B Move backwards by one word.
Alt-F Move forwards by one word.
Ctrl-W Delete the previous word.
Alt-D Delete the next word.
Ctrl-_ Undo.

These shortcuts are provided by the Readline library, which is used by other command-line tools in addition to Bash. For example, you can also use these shortcuts in irb (the interactive Ruby shell).

References