Command History (Linux & Mac OS X)
In a previous post, The ALIAS Command Saves Repetitive Typing, I promised an overview of the way Linux and Mac OS X (and Cygwin on Windows) all keep a history of the commands you issue, even between sessions. The command to display them is history. One use of the history command, for example, might be to explore for commands you frequently enter, thus giving you ideas about which ones ought to be turned into aliases.
The history command displays the last 500 commands you’ve entered (usually).
Like most other Linux commands, the output is sent to “standard out,” meaning it will display on the console unless you redirect it elsewhere (i.e. filter it). For example, to filter it down to just the last 100 commands and then display them one screenfull at a time, use:
history | tail -100 | more
(Actually, the history command has a built-in tail feature. So, you could just enter history 100 | more.)
One of the most common ways to filter the history is to search it using the grep command. For example,
history | grep java
This will come back with all of the commands that contain “java”, something like this:
172 java -jar jedit.jar 303 java -jar ~/java_libs/h2-1.0.74.jar 500 history | grep java
Notice that the command you just entered (history | grep java) is included (on line number 500, in this case). This is because the command history is updated immediately before the history command is processed.
Tip: There are a couple of ways to re-run a command straight out of the history using an exclamation point (!). Typing an exclamation point and the line number will re-execute the command in that position in the history.
Important: The history file scrolls when it reaches a certain limit (usually 500 or 1000), so the numbers change whenever you issue another command. Thus, you have to re-run history | grep every time (which is why it’s better to define an alias for any long commands you use all the time).
You can also type an exclamation point followed by some text. That will cause the system to search backwards through the history for the first line that begins with the text you entered, and then re-execute that command.
Finally, typing two exclamation points (!!) is a shortcut for re-executing the very last command in the history, although you may as well just hist the up-arrow followed by the enter key.
- The ALIAS Command Saves Repetitive Typing
- Auto-Commands at Login
- Learning Linux Commands
- Use Linux Commands and Shell Scripts directly in Windows