If you use the terminal a lot, then you probably know that correcting misspelled commands can become a tedious task, especially if you are dealing with complex and long commands. A common example is forgetting to add sudo at the beginning of a long command which forces you to use your keyboard or mouse in order to correct the command.

Fortunately, Bash  (i.e. the default shell in many Linux distributions) comes with some useful keyboard shortcuts that allow you to easily edit your commands on the fly.


Here is a list of commonly used bash keyboard shortcuts:

Controlling the cursor:


Ctrl + a: jump to the beginning of the line.
Ctrl + e: jump to the end of the line.
Ctrl + p: previous command (i.e. up arrow).
Ctrl + n: next command (i.e. down arrow).
Ctrl + f: go one character forward.
Ctrl + b: go one character backward.
Alt + f: go one word forward.
Ctrl + b: go one word backward.

Editing commands:


Ctrl + t: swap the last two characters (e.g. iv + Ctrl + t ==> vi).
Alt + w: swap the last two words (e.g. systemctl sudo + Alt + t ==> sudo systemctl).
Ctrl + l: clear the screen.
Ctrl + u: delete the line before the cursor position.
Ctrl + w: delete the word before the cursor (only one word).
Alt + u: uppercase the next word (i.e. the word after the cursor).
Alt + l: lowercase the next word.
Alt + c: Capitalize the next word.
Ctrl + _: undo the last movement.
sudo !!: add sudo to the beginning of the last used commad.

Manipulating history:


!xyz: run the last command starting with xyz.
!!: run the last command.
!?xyz?: run the last command containing the string xyz.
^xyz^abc: run the previous command replacing xyz with abc.
!!:$: print the last argument of the previous command:

mkdir -p ~/DIR/newDIR
!!:$
~/DIR/newDIR

NOTE: all these shortcuts work with zshell as well.

Inspired by this Quora answer

Comments