How many times have you retyped the same bash command over and over again or forgotten the the ssh host address that you used last week? If your answer is lots then read on. In this post I discuss the bash history command and how to search for and rerun previous commands that you have typed in your terminal.
Every command that you type is stored in the bash history file. This file is located at
Viewing Bash History
You can view the bash history by typing the following in your terminal:
This will output something similar to the below output:
177 cd /media/filestore/http/ 178 ls 179 ls demo/ 180 exit 181 sudo shutdown now -h 182 history
Here you can see that my last 6 commands were 177) Changing to a different directory, 178) listing the contents of that directory, 179) listing contents a of the demo directory and then 180) exiting the terminal. At some point I must of accessed the server again and 181) shut it down. 182) The final command which was typed is history which displays this output.
The numbers on left of the commands are ids which the history utility uses to identify each stored command. This id is unique so even if you type the same command in twice, each one will have its own history id.
This is a small snippet of the history and the full output can be very long so you need to be able to sieve through it quickly to get the command you want. The beauty with Linux commands is that you can redirect streams to other commands and chain outputs together to form a very powerful set of commands. We will combine the output of the history with the search functionality of grep to find the old command we want.
Searching Bash History
Lets say I want to shutdown and halt this server but I cant remember what the halt flag is (-h). I know I’ve done this before and it should be stored in the bash history. The best way to search the bash history is to pipe the standard output (stdout) of the history command to the grep command and search for specific words that you would of used.
This is shown below:
history | grep "shutdown"
In the example above I am searching through the output of the bash history for any commands that have the word shutdown in them. This will return the following in the terminal:
181 sudo shutdown now -h
Running an old Command from Bash History
To run the command that you have just found you need to append the commands id (181) with an exclamation mark like so:
When you press enter the command stored in the bash history which has the id of 181 will run as normal. In this case the server will shutdown and halt.
In this post I have explained what the history command is, where it is stored, how to search its contents using grep and finally how run a command which is stored in the history.
Other posts related to Bash History