Is there a shortcut for repeat the second proximate command in bash?

You can use !-2:

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

That may not help with your right-hand situation.

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

$ python
$ vim
$ !py
python # 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.


More fun is available. Say you want to keep operating on a file (as above, where you're using, repeatedly):

edit $_
python $_
  • Copy an existing file to
  • Edit (vim, emacs - though why you'd be using a command line if you were running Emacs-OS, I have no idea) - the last word in the previous command line
  • python
  • Edit
  • Edit

History manipulation is such fun. Try man history. Note that the quest to re-use history can result in typing far more than the command itself would. The final command substitution, where I replace by is one such example. Fewer characters to just type in the command and name. :)

The history substitution is also why you get strange messages when you try:

$ echo "This is a disaster!"
-bash: !": event not found

The exclamation mark is being consumed as a history reference, and it can't find a previous command with a double quote.