Bash uses the Readline library for handling command-line input. One of the editing modes supported by the Readline library is the vi mode; the other one being emacs mode. To enable vi mode use the following command.
$ set -o vi
To verify that you are in vi mode, use the command.
$ shopt -o vi
Unlike in Vim, insert mode is the default in bash. Press escape to enter command mode. Most of the Vi commands are available. After you have edited a command in command mode, you can run it by simply pressing enter. No need to go back to insert mode or to the end of the line.
To see keyboard mappings available, run the command:
$ bind -P
If you run this from insert mode, it will show only insert mode mappings. You will notice that most of the commands are not mapped. To see command mode mappings type
bind -P, press escape to enter command mode, and then run the command.
To save a command in history, without running it immediately, prefix it with a #. After recalling such a command from history, the # symbol must be removed before running the command.
Use / and ? to search command history. N and n can be used to search forward and backward for the same term. / and ? cannot be used to search within a command. Please see the next section for a solution.
Using Vim to edit commands
If you want to edit a long command, you might find Readline’s Vi mode somewhat limiting. To use the full power of Vim, press v in command mode. This would open your default editor (most likely Vim) and place the current command in a temporary Vim buffer. Edit the command in Vim and run it using :wq. To quit Vim without running the command use :cq. The :cq command exits vim with an error code. If you use q! to quit without saving, the original command in the command line will be run.
If Vim is not your default editor in bash, please see the documentation for your distribution to see how to make it the default.
The fc command (fix-command) allows you to pull a command from history and edit it using your default editor.