Andreas Gnyp
Andreas Gnyp

Reputation: 1840

Execute a range of commands from history

I am using Ubuntu and I'd like to repeat a bunch of commands I performed. I tried something like

for i in $(seq 2006 2013); do \!$i; done;

but failed, since shell tries to execute a command '!2006'.

man history

also didn't reveal to me how to repeat a range of commands.

Upvotes: 7

Views: 3267

Answers (2)

Lookou
Lookou

Reputation: 49

for i in $(seq 2006 2013); do \!$i; done; 

in your code, you may think ! is like ! in bash command line, but here "!" with the "$i" become a string like string command "!2006, !2007 ... !2013" but actually there is no command named "!2006" "!2006" in whole is a command name.

in Bash ! is a event designator. when you use !2006. it is explained as "reference to command 2006" but not use command "!2006".

! is always left to right execute command.

for more information please visit http://www.gnu.org/software/bash/manual/bashref.html#Event-Designators

I try the following way to get the same result:

for i in $(seq 2006 2013); do  fc -e - $i; done;

Upvotes: 4

Jonathan Leffler
Jonathan Leffler

Reputation: 753695

If you are using bash (or ksh), the fc built-in allows you to manipulate history in various ways.

fc -l                   # list recent history.
fc -l      2006 2013    # list commands 2006..2013
fc         2006 2013    # launch editor with commands 2006..2013; executes what you save
fc -e pico 2006 2013    # launches the editor pico on command 2006..2013
fc -e -    2006 2013    # Suppresses the 'edit' phase (but only executes the first listed command)
fc -e :    2006 2013    # Launches the ':' command (a shell built-in) as the editor

The classic technique in ksh is to use an alias alias r='fc -e -', but because of the behaviour of bash, it is necessary to twist its arm a little harder and use alias r='fc -e :' instead.

Upvotes: 10

Related Questions