RSS Feed

A lesson in bash history

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:

!hist

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:

501 clear
502 less ~/.bash_history
503 history | grep -i ‘mysql’

If I wanted to re-run item 503 I could simply use:

!503

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.

Posted in Linux on the 18th November 2010

3 people have spoken their minds!

  1. IByDev says:

    I use history often but did not know you can use !command to re-run a previously entered command without having to enter it all again or search in the history. Thanks!

SPEAK YOUR MIND...

Your email address will not be published. Required fields are marked *

*