Ben Chuanlong Du's Blog

It is never too late to learn.

Editing Shell Commands Using Vim

Things on this page are fragmentary and immature notes/thoughts of the author. Please read with your own judgement!

  1. A bash prompt can be editted in both Vi mode and Emacs mode. The default is Emacs mode. You can turn on the Vi mode by set -o vi in .bashrc. This will make all bash prompts be edited in a limited single-line Vi mode.

  2. The fc command edits the last shell command (using $EDITOR) and then send it for execution.

  3. The shortcut ctrl+x ctrl+e edits the current shell prompt using $VISUAL or $EDITOR. If you want to use neovim as the editor, add the following configuration into your shell configuration.

    export VISUAL=nvim
    export EDITOR=nvim
    

    This is the recommended way to edit shell prompts as it allows your the full power and flexibility of the Vim editor. For example,

    • You are not limited to single-line editing of a single command.
      • You can span a complicated command to multiple lines using \.
      • You can split a complicated command into multiple simpler commands on multiple lines. On quiting Vim, those commands will be run in sequential.
    • If you find that you need information from historical commands while editing a prompt, you can bring historical commands in using the following command in Vim.
      :r ! fc -ln -10
      

    Notice that the shortcut ctrl+x ctrl+e doesn't work out-of-the-box in the terminal in Visual Studio Code. For more discussions, please refer to Configuraing Terminal in Visual Studio Code
    .

  4. fzf.history allows you to search through shell command history, select one, editing it in $EDITOR, and then send the edited command for execution.

References

Comments