Bash History Display Date And Time For Each Command

HISTTIMEFORMAT

ADVERTISEMENTS



Bash History Display Date And Time For Each Command

How do I display shell command history with date and time under a Linux, MacOS or Unix-like operating systems? How do I see date and time stamps in bash history command running on a Linux or Unix-like systems?The bash shell provides access to the command history, the list of commands previously typed. The value of the HISTSIZE variable is used as the number of commands to save in a history list. If theis set, the time stamp information associated with each history entry is written to the history file, marked with the history comment character. This page shows how to display bash History with date and time when running the history command on a Linux or Unix-like systems.

By default history command will display output as follows:

$ history

Sample outputs:

1994 ls S*.pdf 1995 ls -lh S*.pdf 1996 xdg-open Statement_Jun\ 2018.pdf 1997 xdg-open System_01Jun2018_30Jun2018_0133*.pdf 1998 ssh vivek@ln.cbz01 1999 gpass 2000 history

The above command won’t display what time the commands were executed from the bash history. To solve this problem create a shell variable called HISTTIMEFORMAT.

How to see time stamps in bash history

Defining the environment variable named HISTTIMEFORMAT as follows:

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

OR add to your ~/.bash_profile file, enter:

$ echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bash_profile

Where,

%d – Day %m – Month %y – Year %T – Time

Use the source command to load HISTTIMEFORMAT from file into the current shell script or a command prompt:

$ . ~/.bash_profile

OR

$ source ~/.bash_profile

How to retrieve Linux or Unix bash command line history by date and time

Now, to see history, type:

$ history

Sample outputs:

.... .. 986 11/03/10 04:31:36 memcached-tool 10.10.28.22:11211 stats 987 11/03/10 04:31:36 w 988 11/03/10 04:31:37 iostat 989 11/03/10 04:31:37 top 990 11/03/10 04:31:37 at 991 11/03/10 04:31:38 atop 992 11/03/10 04:31:40 collectl 993 11/03/10 04:31:41 grep CPU /proc/cpuinfo 994 11/03/10 04:31:45 vmstat 3 100 995 11/03/10 04:31:55 sar -W -f /var/log/sa/sa12 .... ..

Here is another output from my Ubuntu Linux server:



Conclusion

You just learned how to display or see time stamps in bash history including date when the command were executed. For more info type the following commands or see gnu/bash page here:

man bash

help history

man 3 strftime

See “A Shell Primer: Master Your Linux, OS X, Unix Shell Environment” for more info.

