The history command in Linux is used to view previously executed commands from the terminal. It will show a list of commands, with an ‘id’ next to each command.
View History Last Executed Linux Commands
The historically run commands are stored in a dedicated file by the Linux shell.
Set History Date and Time for Each Command
The history command also stores the date and time of executing the command, however, does not, by default, show the time of execution of past commands.
To make history show the date as well, we need to set the global variable HISTTIMEFORMAT in the shell to the appropriate format, which can be done using the export command as follows:
$ export HISTTIMEFORMAT='%F %T' $ history
View Linux Command History by Date
Now, you can pipe the above history command output to ‘grep‘ to get a history of commands executed on a particular date.
$ history | grep '2021-01-25'
Similarly, you can also filter the output for multiple key dates.
$ history | grep -E '2021-01-25|2021-01-23'
Using this way, you can specify the dates as patterns for the last
'N' days, or some other combination of dates, and thus get command history for all those dates.
For example, to get command history from the last third to last the fifth date, you can use:
$ history | grep -E '2021-01-23|2021-01-22|2021-01-21'
Now, when we export the variable ‘HISTTIMEFORMAT‘ to the shell profile from the command line, it is exported just for the session, i.e., till the time the terminal is running, after which the variable is removed from the shell profile.
Permanently Set History Date and Time for Each Command
To permanently add the variable to the shell profile, add the export statement to your shell profile file (every command from which runs at the start of a shell).
For example, in the case of ‘Bash‘, run the following to export the variable permanently.
$ export HISTTIMEFORMAT='%F %t' >> ~/.bash_profile
If the file
.bash_profile exists, the operator
'>>‘ will append the export statement to the file, otherwise, it creates the file and writes the statement.
In this article, we have learned how to check the command history of the last few days in Linux. For more information on the history command, make sure you check out its command line manual page by running:
$ man history
Thanks for reading and let us know your questions or thoughts in the comments below!