Bootstrap FreeKB - Linux Commands - history
Linux Commands - history

Updated:   |  Linux Commands articles

Let's run a few commands as a particular user, john.doe in this example.

[john.doe@server1 ]# pwd
/home/john.doe

[john.doe@server1 ]# ls
file1 file2 file3

[john.doe@server1 ]# whoami
john.doe

 

Pressing the up arrow key will display previous run commands. Likewise, the history command can be used to view the current users previously run commands.

[john.doe@server1 ]# history
pwd
ls
whoami
history

 

The history command gets the list of previous run commands from the ~/.bash_history file. Using tail to view the end of the ~/.bash_history file is the same as using the history command.

[user1@server1 ]# tail ~/.bash_history
history
ls
pwd

 

Notice the ~ in ~/.bash_history. The ~ represents the users home directory.

If you are in user1 shell, home is /home/user1:

[user1@server1 ]# echo ~/home/user1

[user1@server1 ]# echo $home
/home/user1

 

If you are in root shell, home is /root.

[root@server1 ]# echo ~/root

[root@server1 ]# echo $home
/root

 

This is significant because it means each user has their own .bash_history file. In another words, commands run by root will be in /root/.bash_history and commands run by user1 will be in /home/user1/.bash_history.

Let's use the SU command with the - option to switch to user1, and then view user1 history. It is very important that we use the - option in the SU command, as the - option will reload the users environment.

[user1@server1 ]# su - user1

[user1@server1 ]# history
history
ls
pwd

[user1@server1 ]# tail ~/.bash_history
history
ls
pwd

 

Root history:

[user1@server1 ]# su - root

[root@server1 ]# history
history
cd /root
whereis ls

[root@server1 ]# tail ~/.bash_history
history
cd /root
whereis ls

 

You probably will want to know the Date and Time that a command was run. Add the following to the ~/.bash_profile file.

export HISTTIMEFORMAT="%m/%d/%y %T "

 

The date and time a command was run will be displayed.

[root@server1 ]# tail ~/.bash_history
 4994  2025/03/31 22:21:56 pwd
 4995  2025/03/31 22:22:06 ls
 4996  2025/03/31 22:27:57 whoami
 4997  2025/03/31 22:36:47 history

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 2c7e5a in the box below so that we can be sure you are a human.