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.
Related: How to configure Bash login scripts
Related: How to set the default text editor in Bash
Related: How to enable Vi keybindings in Zsh
Steps to enable Vi keybindings in Bash:
- 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.
- Ensure the interactive Bash startup file exists.
$ touch ~/.bashrc
Interactive non-login Bash shells read ~/.bashrc when the file exists.
- Back up ~/.bashrc before changing prompt editing behavior.
$ cp ~/.bashrc ~/.bashrc.bak
- Open ~/.bashrc in a text editor.
$ vi ~/.bashrc
Use another editor if vi is not the editor normally used for shell startup files.
- 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.
- Reload ~/.bashrc in the current terminal.
$ source ~/.bashrc
- Confirm that the current shell now reports Vi editing as enabled.
$ shopt -o vi vi on
- 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.
Related: How to configure Bash login scripts
- 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.
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.