Vi Editing Mode for Bash

Setting up vi-mode in BashEver find yourself at the Bash prompt, typing out a very long series of arguments or parameters, only to hideously misspell something at the beginning on the line?

If you’re handy with the emacs editor, you already know the answer. You can use the emacs key bindings to go back and efficiently edit your command line. You don’t need to retype it, or tediously use the arrow keys to go back character-by-character.

However, what if you’re not handy with emacs bindings, but vi bindings? What then?

Fortunately, you can change the command line editing mode used by Bash. The default is emacs-mode, but you can easily change it to vi-mode.

This is accomplished by running the following at the Bash prompt:

set -o vi

Tada! Now you simply need to hit the ESC key, and you can edit the command line using many common vi bindings.

This includes cursor movement commands, such as: $ to move to the end of the line, 0 to move to the beginning of the line, w to move forward a word, of b to move backwards a word.

You can also use actions, such as: dw to delete a word, cw to change a word, i to enter insert mode, or r to replace a character.

Other cursor commands also work: j/k scrolls forwards and backwards in command history, while h/l move the cursor backwards and forwards a single character at a time.

Note that changing the editing mode to vi-mode will disable the default emacs keybindings such as Alt + Del. You can restore emacs-mode by running set -o emacs, or by starting a new terminal session.

While this isn’t necessarily a better way, it can be much more efficient for people (such as myself) who are more familiar with vi than with emacs.

Placing set -o vi in your .bashrc or .bash_profile file ensures you always have vi-mode editing available.

This also works on Mac OSX if you are using Bash as your shell.