# A Command A Day - history # The history Comand The history command is one of those rare commands that could change the way you live on the bash terminal, as it is a bash command that will show you the last commands to be entered in the users session. There are two states for history contents: 1. The history list (in memory) 2. The history file (on disk) When you type the `history` command into your terminal, you are interacting with your history list in memory, which will show you the last commands executed in your running session. Once you log out, your comands will be written to disk in the file `~/.bash_history` This command is useful, because when you interact with a terminal often it can be difficult to remember or even re-enter commands that you may have executed when you are in long running sessions. ## Re-execution Now that we can see the commands that we have executed, we can then re-execute these commands if need be. Once you execute the `history` command, you will see the list of commands and their line numbers: ``` [jayson@RyterINC ~] history 1 echo test1 2 echo test2 3 echo test3 4 echo test4 5 echo test5 6 echo test6 7 echo test7 8 echo test8 ``` If you wanted to rerun a command, let's say `echo test4`, you use `!` plus the index of the command like so: ``` [jayson@RyterINC ~] !4 echo test4 test4 ``` ## Searching through history Piping history with `grep` is incredibly useful. ``` [jayson@RyterINC ~] history | grep echo 1 echo test1 2 echo test2 3 echo test3 4 echo test4 5 echo test5 6 echo test6 7 echo test7 8 echo test8 11 echo test4 12 history | grep echo ``` ## Deleting history We can delete history via the history list which is in memory, or we can delete it from the on disk file `~/.bash_history`. To delete our history from memory, we can simply use the command `history -c`. From the man pages: ``` -c Clear the history list. This may be combined with the other options to replace the history list completely. ``` To clear the file, we can write `/dev/null` to the file itself: ``` cat /dev/null > ~/.bash_history ``` Because history is kept in memory, your current session is going to write to the file once you logout. To prevent this, you can chain together some commands to make this seamless: ``` cat /dev/null > ~/.bash_history && history -c && exit ```