By default, most shells use emacs-style key bindings for command-line editing and modification. For users of vi or vim, however, you can instead configure shells to use vi key bindings instead. This is done by editing ~/.bashrc in the case of bash, or ~/.zshrc in zsh and adding:
set -o vi
in bash, and the following for zsh:
Once you have saved either ~/.bashrc or ~/.zshrc, exit the shell and open a new terminal.
By default, you will be in insert mode, which means that you type as you normally would. Commands like [Ctrl]A or [Ctrl]E no longer work, however. To get into command mode, press [ESC] (as you would in vim) and use vi key commands to navigate the command line, such as $ to go the end of the line or 0 to go to the beginning of the line.
From that point, you can use other vi commands:
- b to go back one word
- 2b to go back two words
- dw to delete a word
- dd to delete the entire line
- d$ to delete from the current cursor position to the end of the line
- d0 to delete from the current cursor position to the beginning of the line
- w to go forward one word, and so forth
To return to insert mode, simply type i, as you would in vi, and you can edit the command line as you normally would.
If you are more familiar with vim than emacs, using vi key bindings in your shell makes a lot of sense and will make working in the shell much easier as you will be using edit commands that you are already familiar with.
If you use emacs more often, leave the defaults as they are to use the various commands you would normally use in emacs. On the other hand, if you use neither, choose a style that makes the most sense and makes using the command line faster and more efficient.
Subscribe to the Developer Insider Newsletter
From the hottest programming languages to commentary on the Linux OS, get the developer and open source news and tips you need to know. Delivered Tuesdays and Thursdays