Mac OS X,  Mac OS X Server,  Mac Security,  Mass Deployment,  Ubuntu,  Unix

Bash History Fun

We tend to use a lot of commands in the Terminal app. That is, after all, what it’s there fore. And there’s a nice history of what we do. There are also a number of ways to view and manage the bash history. The simplest of which is the history command, which will show the previous commands run. Here, we’ll simply run it:

history

Keep in mind that this shows the history based on context, so if you sudo bash, you’ll potentially see a different history. You can also use the bash built-in fc command, which has the additional awesomeness of being able to edit and re-run commands from the history. To start, we’ll simply look at showing the last 16 commands using the -l option:

fc -l

You can also constraint entries in the output by specific line numbers. For example, to see lines 12 through 18, simply use them as the first two positions of the command after fc:

fc 12 18

You can load the history into an editor and remove or add entries using fc without any options:

fc

To exit the editor, hit control-z. I’ve written in the past about using substitution. For example, sudo !! to run the last command. fc can do some basic substitution as well. For example, use the -s to start substation and then enter a string, which will append whatever you like before a command. So the following would put sudo in front and re-run the previous command:

fc -s sudo

And let’s say that you were doing a find for a string of krypted. To then swap that string with charles:

fc -s krypted=charles

Overall, the bash history can be incredibly useful. I frequently pipe the output of a series of lines into a new file with a .sh at the end as a starting point for scripts and use these substitution options to save myself a bunch of time not retyping longer commands. Enjoy.