Get the Most Out of Bash History
More About Bash
More About BashTip of the Trade: Type 'history' at the Bash command prompt, and you'll get a list of your previous commands. Sure, you can scroll up and down to find the ones you're looking for, but did you know there are faster ways to find what you need as well as handy shortcuts to making use of them.
Type history at the Bash command prompt, and you'll get a list of your previous commands. You can navigate through these with the up and down arrows, but there are other ways of interacting with them that I've been investigating this week. One straightforward option is to use the number at the start of the line to refer to the command. So,
will execute the line numbered 15268. !! executes the last command, and !-2 will execute the last-but-two command.
You can edit previous commands quickly using :s///. For example, if you typed 'temp' when you meant 'tmp' in command 15200, use this to correct it:
To do this, edit with the previous command, use !!:s/temp/tmp/, or the shortcut ^temp^tmp. Using the g global modifier changes every occurrence of the word, not just the first one:
You can also edit a block of commands. Let's say you executed a series of commands, between numbers 1478 and 1482, with a particular value, and want to edit them all. (Maybe you did a series of things to a file or a directory, and now want to repeat the sequence with another file.) Use this command:
fc 1478 1482
The lines will be opened up in your preferred editor, where you can edit them, save and exit, and they'll be run (as edited) immediately. (And then added, in their edited form, to your history!)
Check out the bash manual for more things you can do with the history.
Juliet Kemp has been messing around with Linux systems, for financial reward and otherwise, for about a decade. She is also the author of "Linux System Administration Recipes: A Problem-Solution Approach" (Apress, 2009).