Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This question already has an answer here:

In bash you can repeat the last command by entering !!, or the third last command !-3 for example.

Is there a quick way to repeat the last 3 commands, without having to type out !-1; !-2; !-3 explicitly?

share|improve this question

migrated from stackoverflow.com Mar 4 '12 at 10:06

This question came from our site for professional and enthusiast programmers.

marked as duplicate by derobert, chaos, slm Sep 9 '14 at 16:38

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3 Answers 3

up vote 31 down vote accepted

fc -N -1

Where the -N is the last N commands you want to repeat.

This will open an editor with the last N commands in it. You can edit the commands as desired and when you close the editor, they will all be run in sequence.

share|improve this answer
TIL about fc. –  Zsolt Botykai Mar 3 '12 at 18:34
As a 10 year Linux user, never knew of this. Thanks. –  stefgosselin Mar 9 '12 at 0:00
What about calling them in the same sequence they were run? –  digiout Nov 18 '14 at 12:15
@digiout That should be the normal behavior. You can reverse it if you would like with -r. –  Swiss Nov 18 '14 at 19:14
on a mac you want to use -0 instead of -1 –  miah Feb 25 at 3:48

You could also turn this problem upside-down and group those 3 previous commands, for example:

echo 1; echo 2; echo 3

and then you will be just fine writing !!.

share|improve this answer
+1 for elegance :) –  Vic Mar 3 '12 at 17:37

Well, not what you expect, but this works:

history | fgrep -v history | tail -3 | sed 's_^ *__' | cut -f 2- | bash

And you can create a function for this:

    history | egrep -v 'history|myFunc' | tail ${1} | sed 's_^ *__' | cut -f 2- | bash

So you can call it like:

myFunc -3     
share|improve this answer
The result of history | tail -3 | cut -f 2- still contains numbers on my machine, because cut removes only the one leading space. –  Rafał Rawicki Mar 3 '12 at 12:38
On many systems sh will not generate the same result as bash, even if sh is a symbolic link to bash. –  user unknown Mar 3 '12 at 12:57
@RafałRawicki with the addition of sed problem solved. @userunknown bash can be used too. –  Zsolt Botykai Mar 3 '12 at 14:32
This is just far too roundabout a way to achieve what is intended, sorry. –  Swiss Mar 3 '12 at 17:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.