Using vi commands in your bash shell

2 minute read

Entering a long shell command and then moving the cursor around to correct parts of it always felt a bit clunky to me. I remembered some of the <ctrl>/<alt> key bindings but would often just end up using arrow keys or alt-click to navigate to a certain position.

Today I learned that you can easily get a vi-style command line interface in bash, giving you insert and normal mode and allowing you to use a basic subset of vi commands.

While an ancient feature, it was new to me. Here’s how to do it.

Set shell option for vi-style editing

To enable vi-style editing, you set the vi option:

set -o vi

If you want to keep using the option, make sure to add it to your .bash_profile or .bashrc.

Start making your edits

Once you have the above command executed, you can start using the cli just like vi.

A couple of things to be aware about:

  • You are directly placed in insert mode, not in normal mode.
  • This is not a full vi, so don’t expect every command to work.
  • You can get a full vi/vim, if you really want to 🤓 (see next section).

More complex edits

If the implemented commands are not enough to edit your one-liner, you can always request a fully-fledged vim and open the command in a temp file.

To do that, press v while in normal mode. This will open your default editor with a temp file. Write-quit to execute the edited command in the shell.

In case this doesn’t work for you, you might want to check your setting for $VISUAL or add this to your .bash_profile: export VISUAL="vim"

Leave a Comment