History Command Examples

Before we look at History Command Examples. Let’s brief about it. The history command is used to check the history of the commands which are executed previously. Many people also prefer it to call bash history.

History Command Examples
A wise man said it right 🙂

The history of the file is basically stored in the /home/user/.bash_history. However, you can check the location of the history file using the command echo $HISTFILE.

To check the location of the file where the history of the command is being stored.
[user@server~]$ echo $HISTFILE

If you check the same thing for the root user.

[root@server~]# echo $HISTFILE

History command normally stores around 1000 commands, after that new commands are replaced with the old ones. However, you can check how many commands your machine is storing by using the command below.

[root@server~]# echo $HISTSIZE

You can also change the number but putting the line below in .bash_profile.

# vi ~/.bash_profile
export HISTSIZE=500

If you look at the history of the commands, you will see that it will just show the commands which have been running, however, there is no indication of the date and time. You can add the date and time to the history command using the command below.

echo export HISTTIMEFORMAT=\"%m/%d/%y %T \" >> ~/.bash_profile

Please remember that the history command is saved in the file after the user has exited the session, till then it’s stored in the history buffer.

Now let’s dive into the history command, without any delay. To check the history of the commands simply run the history on the command line.

[root@server ~]# history
    1  whoami
    2  clear
    3  ls
    4  whoaami
    5  ls -ltr
    6  top -c
Check the last 5 commands in history use history 5
[root@server ~]# history 5
   92  clear
   93  whoami
   94  top -c
   95  history
   96  history 5
To clear history use history -c
[root@server ~]# history -c
[root@server ~]#
[root@server ~]# history
    1  history
To delete a particular command in history use history -d
[root@server ~]# history 5
1 history
2 whoami
3 clear
4 hisry 5
5 history 5

here I’m deleting the command which I fired at the 4th Number

[root@server ~]# history -d 4
[root@server ~]# history
1 history
2 whoami
3 clear
4 history 5
5 history -d 4
6 history

To run a command at a particular number in history you can use! followed by the number. For example, if you want to run the command at number 2 the run !2. I normally don’t use this method because it’s dangerous if you don’t exactly remember the number of the command exactly.

[root@server ~]# !2
Wrap up

A history command is a useful tool in Linux especially when you want to investigate or monitor what users have done. Hopefully, you have learned all this with History Command Examples.

Leave a Comment