Bash Command Line – How to Execute Consecutive Commands from History

bashcommand historycommand line

Suppose I want to execute a sequence of four commands that I have executed before. If the first one is 432 in the command-history, then I could do:

$ !432; !433; !434; !435

I'm curious, is there a more efficient way to accomplish this?

Best Answer

If it refers to commands run just recently, a more efficient way is to reference them with negative numbers:

!-4; !-3; !-2; !-1

Also, once you do it, your last history entry will contain the whole chain of commands, so you can repeat it with !!.


Edit: If you haven't already, get familiar with the great builtin function fc, mentioned by Gilles. (Use help fc.) It turns out that you can also use negative numbers with it, so you could do the same as above using

eval "`fc -ln -4 -1`"

This has one caveat, though: after this, the eval line is stored in the history as the last command. So if you run this again, you'll fall into a loop!

A safer way of doing this is to use the default fc operation mode: forwarding the selected range of commands to an editor and running them once you exit from it. Try:

 fc -4 -1

You can even reverse the order of the range of commands: fc -1 -4

Related Question