Run a Previous Command Using a String


The capability to run a command again by referencing its number is nice, but it requires that you know the command's number in history, which can be tedious to discover (piping the output of history to grep would help, but it's still not optimal). Often a better way to reference a previously entered command is by the actual command's name. If you follow the exclamation point by the first few letters of that command, your shell runs the first command it finds when looking backward in .bash_history.

$ cat /home/scott/todo Buy milk Buy dog food Renew Linux Magazine subscription $ cd /home/scott/pictures $ !cat cat /home/scott/todo Buy milk Buy dog food Renew Linux Magazine subscription 

If the cat command is found three times in your historyat 35 (cat /home/scott/todo), 412 (cat /etc/apt/sources.list), and 496 (cat /home/scott/todo)and you enter !cat, the one found at 496 is the one that runs. If you want to run the cat found at 412, you need to run either !412 or follow the exclamation mark with enough information so it can tell you're referencing the command listed as 412.

$ !cat /etc cat /etc/apt/sources.list deb breezy main restricted deb-src breezy main restricted 

Because humans have a far easier time remembering words instead of numbers, you'll probably end up using this method for invoking past commands. If you're ever unsure, run history and take a look.

Linux Phrasebook
Linux Phrasebook
ISBN: 0672328380
EAN: 2147483647
Year: 2007
Pages: 288

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: