Linux: How to include timestamps to history output
The history command in Linux and Unix-like operating systems is used to display a list of previously executed commands in the current shell…
The history command in Linux and Unix-like operating systems is used to display a list of previously executed commands in the current shell session. It provides a way for users to view and access their command history, which can be useful for various purposes like recalling the syntax of a command or remember what you have run in the past, but history on its plain form does not provide timestamps so we cannot be sure when a command executed, lets see how we can change this!
Usage of the history command in bash
by just entering history in a bash shell we get a similar output, the command and its number, useful but as we said no timestamp ..
990 uptime
991 top
992 su - root
993 clear
994 su - root
995 exit
996 crontab -l
997 su - root
998 exit
999 su - root
1000 su - root
1001 ls
1002 historyHow to add timestamp to history
In bash shell the environment variable that controls history command formatting is HISTTIMEFORMAT , to define timestamp along with command enter the following in the terminal
export HISTTIMEFORMAT='%F %T 'Now lets try history again, we can see that now each entry has the timestamp that the command issued
990 [08/24/23-14:23:18] uptime
991 [08/24/23-14:23:38] top
992 [08/24/23-14:24:12] su - root
993 [09/02/23-21:01:33] clear
994 [09/02/23-21:01:35] su - root
995 [09/02/23-21:20:01] exit
996 [09/05/23-15:51:59] crontab -l
997 [09/05/23-15:52:01] su - root
998 [09/06/23-11:24:10] exit
999 [09/18/23-14:20:38] su - root
1000 [09/18/23-15:43:13] su - root
1001 [10/02/23-15:21:57] ls
1002 [10/02/23-15:22:05] historyThis environment variable will lost after session end so we would want to make the change permanent, to do this append the environment variable to ~/.bashrc , this file is readed every time a user starts a new bash session.
History command in other shells
Other shells like zsh and fish have a history command as well but they use a different environment variable to modify its formatting
Zsh Shell
If you’re using the Zsh shell, you can achieve the same by adding the following line to your ~/.zshrc file:
HIST_STAMPS="yyyy-mm-dd HH:MM:SS"Fish Shell
Fish shell stores its history differently, and you can enable timestamps using the following commands:
set -U fish_history show_time yes
set -U fish_history time_format '%Y-%m-%d %T 'Now, you should be able to use the history command in your shell to view your command history with timestamps included. Each command will be preceded by a timestamp indicating when it was executed.
Conclusion
In this article we saw how we can modify the history environment variable options to add timestamp formatting, quite easy to add a very useful feature! i hope you enjoyed this article as much i enjoyed writing the article!