Wednesday, May 16, 2012

Re-executing a command from History after substitution

At times we might be executing a long command on Shell prompt and later we might have to re-run that same command-set with one small change. It will be real pain to type the same command-set again just for a one parameter change. Linux has a Bash built-in command called 'fc' (stands for find command) using which we can make this task simple.

Illustration:
Let's say you have executed the following command (bit long) some time ago:
"bash /root/itc/hc/dyn/nmon -f -t -m /var/log/nmon -s300 -r iss-365-rhel5664-tmpl.xyz.com -c196"
Now you wish to execute the same command with one value changed in it. Instead of -s300, you want to re-run the command with the new value -s200.
hostxyz # fc -l               <-- Will list 16 most recent commands
427      ls
428      ls -l
429      vim NMON_startup_script.sh-May-16-12.log
430      sh /root/itc/hc/dyn/NMON_startup_script.sh
431      cat NMON_startup_script.sh-May-16-12.log
432      uptime
433      perl /opt/sysinfo.pl
434      ls -l /var/lock/subsys
435      bash /root/itc/hc/dyn/nmon -f -t -m /var/log/nmon -s300 -r iss-365-rhel5664-tmpl.xyz.com -c196
436      cd ~ashok
437      ls
438      ps -ef | grep nmon
439      kill -15 3384
440      date
441      fc -l
442      ps -ef | grep nmon
hostxyz # fc -s s300=s200 bash      
bash /root/itc/hc/dyn/nmon -f -t -m /var/log/nmon -s200 -r iss-365-rhel5664-tmpl.xyz.com -c150
hostxyz #
With the `fc -s [pat=rep ...] [command]' format, the command starting with 'bash' is re-executed after the substitution OLD=NEW is performed.
Note:  Typing just 'fc' will open the last command in Text Editor. If you want to open range of commands that you executed before in Text Editor, you can use the following syntax:  # fc [Start no]  [End no].

1 comment:

  1. @Mahasiswa, I'm glad that my postings helped you :) Keep reading. Thanks !

    ReplyDelete