Bash: Edit command in your editor and execute directly

chinmay chhajed - Feb 20 '21 - - Dev Community

Sometimes we need to enter same command multiple times by changing 1 or 2 arguments. This is very tedious job to do. Update and execute command every single time!

But worry not as what you are going to see in next few minutes will act as a big time savior in such cases.

If you use shell in default mode (emacs if you don't know :P), you can press ctrl-x ctrl-e and enter text editor to edit all the commands together by using features of your editor like copy, paste visually select etc. Save and exit editor to execute all the commands.

If you are using vi mode, you can move to normal mode by pressing Esc and then pressing v would achieve similar functionality.

You can switch between vi and emacs mode by commands set -o vi and set -o emacs respectively. Your keybindings will work according to your mode.

For my work, I use this script poolfetch a lot with arguments varying only 1 or 2 characters. This functionality is very handy for me at such times.

Here is a sample usage of this feature in emacs mode:

change3

Edit:

As suggested by Tai Kedzierski here, you can choose the editor in which you want to edit commands by setting environment variable EDITOR or VISUAL.

It's a good idea to set them in $HOME/.bashrc or $HOME/.profile. Former one will set it for every bash instance and latter one will set it globally which will be done at time of system startup. I prefer latter one.

. . . . . . . . . . . .