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"

Like to comment? Feel free to send me an email or reach out on Twitter.

Did this or another article help you? If you like and can afford it, you can buy me a coffee (3 EUR) ☕️ to support me in writing more posts. In case you would like to contribute more or I helped you directly via email or coding/troubleshooting session, you can opt to give a higher amount through the following links or adjust the quantity: 50 EUR, 100 EUR, 500 EUR. All links redirect to Stripe.