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.

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.

3 Answers 3

up vote 28 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

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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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