Lesson 67: history Command
In this lesson, you'll learn how to use the history command to view, search, and manage your command history in Linux.
We use the history command is frequently used in our daily routine jobs to check the command history or get information about commands executed by the user.
It effectively extracts the command that was executed by users in the Bash shell. This may be useful for audit purposes or to find out what command was executed at what date and time.
By default, the date and timestamp won't be seen while executing the history command.
However, the Bash shell provides CLI tools for editing the user's command history.
Let's understand the working of history commands with the help of some examples.
history Command Syntax
$ history [OPTIONS]
history Command Options
| Option | Description |
|---|---|
-c |
Clear/delete all entries from the bash history list |
-d OFFSET |
Delete the history entry at the specified offset |
-w |
Write the current history to the history file |
-r |
Read the history file and append it to the current history |
-n N |
Display only the last N entries from history |
1. List Last/All Executed Commands
Executing a simple history command from the terminal will show you a complete list of the last executed commands with line numbers.
[ubuntu@TecMint ~]$ history
1 PS1='\e[1;35m[\u@\h \w]$ \e[m '
2 PS1="\e[0;32m[\u@\h \W]$ \e[m "
3 PS1="\u@\h:\w [\j]$ "
4 ping google.com
5 echo $PS1
6 tail -f /var/log/messages
7 tail -f /var/log/messages
8 exit
9 clear
10 history
11 clear
12 history
2. List All Commands with Date and Timestamp
How to find the date and timestamp against a command? The export command with the variable will display the history command with the corresponding timestamp when the command was executed.
[ubuntu@TecMint ~]$ export HISTTIMEFORMAT='%F %T '
1 2023-08-09 10:40:12 cat /etc/issue
2 2023-08-09 10:40:12 clear
3 2023-08-09 10:40:12 find /etc -name *.conf
4 2023-08-09 10:40:12 clear
5 2023-08-09 10:40:12 history
6 2023-08-09 10:40:12 PS1='\e[1;35m[\u@\h \w]$ \e[m '
7 2023-08-09 10:40:12 PS1="\e[0;32m[\u@\h \W]$ \e[m "
8 2023-08-09 10:40:12 PS1="\u@\h:\w [\j]$ "
9 2023-08-09 10:40:12 ping google.com
10 2023-08-09 10:40:12 echo $PS1
Meaning of HISTTIMEFORMAT variables:
%F- Equivalent to%Y-%m-%d%T- Replaced by the time (%H:%M:%S)