Bash – shortcut for repeat the second proximate command in bash

bashcommand historycommand line

We all know that !! can repeat the last command you do in bash.

But sometimes we need to do some operation like

$ python test.py
$ vim test.py

$ python test.py # here is where I need to repeat the second proximate bash command

I can use up-arrow key to do that, but that requires me to move my right hand away to an uncomfortable position. So I'm wondering if there is a command which like !! would work?

Best Answer

You can use !-2:

$ echo foo
foo
$ echo bar
bar
$ !-2
echo foo
foo

That may not help with your right-hand situation.

You can also use !string history searching for this sort of case:

$ python test.py
$ vim test.py
$ !py
python test.py # Printed, then run

This may be more convenient to use. It will run:

the most recent command preceding the current position in the history list starting with string.

Even just !p would work. You can use !?string to search the whole command line, rather than just the start.

Related Question