How to view and edit command history in Linux

Home > Search > How-to
  by

Let's run a few commands:

[user1@server1 ]# pwd
/home/user1

[user1@server1 ]# ls
file1 file2 file3

[user1@server1 ]# whoami
user1

 

In Terminal, pressing the up arrow key will display previous run commands. Likewise, the HISTORY command can be used to view previous run commands.

[user1@server1 ]# history
history
ls
pwd

 

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
498 10/28/16 04:57:25 history
499 10/28/16 04:57:37 cd /root
500 10/28/16 04:57:55 whereis ls

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments