DEV Community

loading...

History Is Your Friend

paulmicheli profile image Paul Micheli Updated on ・2 min read

Linux History Command

If you leverage and utilise the command line history, you can save a lot of time on a daily bases. You can also use it to gain a better under standing of how a newly discovered server is administrated by viewing the history of commands run.

How does it work?

Just run the command;

paulmicheli@minime:~$ history
   23  sudo apt install python3.8
   24  sudo apt update
   25  sudo apt install software-properties-common
   26  sudo add-apt-repository ppa:deadsnakes/ppa
   27  sudo apt update
   28  sudo apt upgrade
   29  sudo apt install python3.8
   30  sudo apt install python
   31  sudo apt-get install python3.6
   32  sudo reboot

A date & time stamp is always helpful

Having a time stamp of when the command was run can help im many different ways.

For this to happen you will need to add the below to your .bashrc file and reload using the source command;

## History timestamp
export HISTTIMEFORMAT="%h %d %H:%M:%S "
export HISTSIZE=50000
export HISTFILESIZE=50000
paulmicheli@minime:~$ source ~/.bashrc

Now when you run the history command you'll see the date and time;

paulmicheli@minime:~$ history
   23  Sep 07 13:52:23 sudo apt install python3.8
   24  Sep 07 13:52:23 sudo apt update
   25  Sep 07 13:52:23 sudo apt install software-properties-common
   26  Sep 07 13:52:23 sudo add-apt-repository ppa:deadsnakes/ppa
   27  Sep 07 13:52:23 sudo apt update
   28  Sep 07 13:52:23 sudo apt upgrade
   29  Sep 07 13:52:23 sudo apt install python3.8
   30  Sep 07 13:52:23 sudo apt install python
   31  Sep 07 13:52:23 sudo apt-get install python3.6

  • the two additional arguments I have added increase the history size

How to use it

Command Example Description
!n !27 Execute nth command in history
!! !! Execute the previous command
blah !ls run the most recent command that starts with ‘blah’
!blah:p !ls:p print out the command that !blah would run
!* !* the previous command except for the last word
!$ !$ Last argument of last command
!^ !^ First argument of last command

Reverse searching

Press the ctrl key and the r key simultaneously. The below prompt will appear;

(reverse-i-search)`': 

Start typing the bit of the command you remember and you will see the most recent match from your command history;

(reverse-i-search)`ocke': docker ps

press ctrl+r again to cycle through all your history that match this search term.

(reverse-i-search)`ocke': docker stop 35e0e91e92de

Removing history

There may come a time that you want to remove some or all the commands in your history file. If you want to delete a particular command,

enter history -d <line number>

To clear the entire contents of the history file, execute

history -c.

The history file is stored in a file that you can modify, as well.
Bash shell users find it in their home directory as .bash_history.

Discussion

pic
Editor guide