DEV Community

chinmay chhajed
chinmay chhajed

Posted on

Bash: Edit command in your editor and execute directly

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:



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.

Top comments (2)

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)"
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 ;-)

victoryarema profile image
Victor Yarema • Edited

The article is great. I started to use vim to edit long scripts now. I was "suffering" with emacs mode in zsh before.
But regarding your example with poolfetch. I would do it compltely different. Here's an example:

seq 4 | xargs -n1 bash -c 'poolfetch -g $1.esp32' -
Enter fullscreen mode Exit fullscreen mode

You can even add -P 32 for example if you want to run at most 32 parallel jobs. Obviously in current example it will trigger just 4 parallel jobs. One of few things to beware in such case is that all the outputs from parallel jobs will interleave and it can be messy.