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:
- The history list (in memory)
- 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:
|
|
If you wanted to rerun a command, let’s say echo test4
, you use !
plus the index of the command like so:
|
|
Searching through history
Piping history with grep
is incredibly useful.
|
|
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:
|
|
To clear the file, we can write /dev/null
to the file itself:
|
|
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:
|
|