How to enable Vi keybindings in Bash

Vi keybindings make the Bash prompt use insert and command modes, so long history entries can be corrected with vi movement and change keys instead of arrow-key editing. Enable them when command-line editing habits already come from vi or Vim and the Bash prompt should behave the same way across terminal sessions.

Bash prompt editing is handled by Readline. The set -o vi shell option switches the current interactive Bash session from the default Emacs-style editing mode to Vi-style line editing, where Esc enters command mode and i returns to insert mode.

Store the setting in ~/.bashrc when interactive Bash shells should start in Vi mode. The verification step starts a new Bash process with that startup file, so the result proves the saved file loads the setting instead of only changing the current terminal.

Steps to enable Vi keybindings in Bash:

  1. Check whether Vi editing is already enabled in the current Bash shell.
    $ shopt -o vi
    vi                  	off

    If the output is on, the current shell is already using Vi keybindings.

  2. Ensure the interactive Bash startup file exists.
    $ touch ~/.bashrc

    Interactive non-login Bash shells read ~/.bashrc when the file exists.

  3. Back up ~/.bashrc before changing prompt editing behavior.
    $ cp ~/.bashrc ~/.bashrc.bak
  4. Open ~/.bashrc in a text editor.
    $ vi ~/.bashrc

    Use another editor if vi is not the editor normally used for shell startup files.

  5. Add the Vi editing option near the end of ~/.bashrc.
    ~/.bashrc
    set -o vi

    If the file already contains set -o emacs, replace that line or place set -o vi after it because the later setting controls the final editing mode.

  6. Reload ~/.bashrc in the current terminal.
    $ source ~/.bashrc
  7. Confirm that the current shell now reports Vi editing as enabled.
    $ shopt -o vi
    vi                  	on
  8. Start a new interactive Bash process with the same startup file and confirm the setting loads there too.
    $ bash --rcfile ~/.bashrc -ic 'shopt -o vi'
    vi                  	on

    The --rcfile ~/.bashrc option makes the test shell read the edited file directly. A login shell may need .bash_profile or .bash_login to source ~/.bashrc before the setting appears in every terminal session.

  9. Open a new terminal, press Esc at the Bash prompt, and use Vi command-mode keys such as h, l, b, w, or i to edit a test command.

    Terminal applications can intercept some key combinations before Bash receives them, so test the keys in the terminal profile used for daily shell work.