Have you ever wondered how it is that you can skip back and forwards throughout your history of commands on bash? Well it’s pretty simple, bash keeps a log of all commands you enter in a file called bash_history in the root of your home directory.
This file is very simple and consists of a list of all previously entered commands, however, before writing to the history file bash stores your history of commands in a buffer and upon logging out of your shell writes that buffer to ~/.bash_history. This is worth noting if you plan on modifying the history, in order to modify the latest commands entered into the bash history you will need to log out and then back in again to see updates to the file.
Viewing your history
There is no need to directly read the contents of ~/.bash_history, you can simply run the history command which output your entire history. If you, for example, only need the last 10 commands stored in your history you can tail the output.
history | tail
Filter for a specific command
You can filter for a specific command you previously entered using grep, like so:
history | grep -i ‘command’
Run the last command
You can run the last specific command you entered by prepending the beginning of the command with an exclamation mark. For example, if earlier that day you ran a command to look at your history, grepping for any commands relating to MySQL, such as:
history | grep -i ‘mysql -u root’
You can rerun that history command by simply running:
Or, if you know the buffer point of a command you entered you can specify that number after the exclamation mark. For example, here’s the last three commands in my history:
502 less ~/.bash_history
503 history | grep -i ‘mysql’
If I wanted to re-run item 503 I could simply use:
Of course you could simply use reverse-i-search but knowing the ins and out of history can save you time.
Be smart, be safe
If you know other users will be logging on as the same user make sure you clear the history log of all commands you do not wish them to see. For example, connecting to MySQL and specifying a password in the command will be stored in your history, make sure you clear this command in the history or enter the command without a password and only enter when prompted.
You can edit ~/bash_history with your favourite editor.