Skip to main content

Edit previous commands in shell before running them

Let's say you run a certain command with some parameters (like opening a file in vim). Then you want to run basically the same command, but instead of opening the file in vim, you just want to view the contents with cat.

The most common way of doing this would be either:

  • Writing the whole command again like this (very slow)
    sudo cat /etc/apt/sources.list.d/nginx.list
  • Clicking the arrow up button on you keyboard to bring up the previous command (sudo vim /etc/apt/sources.list.d/nginx.list) and then changing vim to cat by moving the cursor using arrow key on the line or some other shortcut
    • This is the way I usually used to do it, but found it oftentimes pretty tedious - especially jumping to the word, deleting it and writing a new one

Recently I found out you can do it a different way and it's acually better for my workflow once I got used to it.

  • Run the command you want to run first
    sudo vim /etc/apt/sources.list.d/nginx.list
  • Then if you want to do the same thing, but just with cat, write this in the shell and then hit enter
    !!:gs/vim/cat

As you can see below, this will run the previosprevious command, but replacing the word vim with cat

user~$ vim /etc/apt/sources.list.d/nginx.list
user~$ !!:gs/vim/cat
cat /etc/apt/sources.list.d/nginx.list
deb [signed-by=/usr/share/keyrings/nginx-archive-keyring.gpg] http://nginx.org/packages/mainline/debian bookworm nginx

This can be useful e.g when you edit a file and then want to print out the edited contents into the shell to copy to a ticket or documentation for example