DEV Community

loading...

Bash: Edit command in your editor and execute directly

chhajedji profile image chinmay chhajed ・2 min read

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.

Discussion (1)

pic
Editor guide
Collapse
taikedz profile image
Tai Kedzierski

Note that for this to work, there must be a default editor set. Normally this is pre-setup by most distros and systems - but! This generally defaults to Nano.

You can override this by setting the EDITOR environment variable (and for good measure, the VISUAL variable too.

This will do the trick (and not repeat itself if it's already done !)

grep -P '^(VISUAL|EDITOR)=' "$HOME/.basrhc" &>/dev/null && cat EOF >> "$HOME/.bashrc"
export EDITOR="$(which vim)"
export VISUAL="$EDITOR"
EOF
Enter fullscreen mode Exit fullscreen mode

It checks whether VISUAL or EDITOR are set, and if neither is set, adds the vim editor as default editor. You can replace this with any other command line text editor you care for - normally one of vim emacs or nano. If you know, you know ;-)