History command displays the list of commands that have been executed from a terminal. By default, it shows the only commands executed by users and it doesn’t include date and time in its output.
There can be some variations in how history command behaves, It depends on which shell you are using whether it is bash, ksh, c shell, or some other. So in this article, we will discuss the bash version of history command.
The HISTTIMEFORMAT environment variable
Whenever you run history command it looks for an environment variable HISTTIMEFORMAT, which tells how to format date and time with the history command. If its value is not set then it will display the default result that is output without date and time.
This variable takes value from strftime which converts date and time to a string. The following values can be used with this variable –
%T – It will be replaced by %H:%M:%S
Where,
%H -Hours
%M- Minutes
%S- Seconds
%F – Replaced by %Y- %M- %D
Where,
%Y- Year
%M- Month
%D- Day
The default output of the history command
If you execute the following command, you will see the default output of the history command. It contains the list of previously executed commands from the terminal –
history
How to display bash command history by date and time?
There are various ways by which you can display date and time with the history of commands.
Display date and time for current user temporarily
Execute the following command to set the HISTTIMEFORMAT variable. This will display date and time for the current user temporarily the changes will go away after the system reboot.
export HISTTIMEFORMAT ='%F %T '
Now after executing this command if you run –
history
Display date and time permanent for all user
To make changes permanent for all users we will append HISTTIMEFORMAT variable to /etc/profile. Now execute the following commands in your terminal –
echo 'HISTTIMEFORMAT="%F %T "' >> /etc/profile
And then run the command to make changes effective –
source /etc/profile
Append HISTTIMEFORMAT to .bashrc_profile
To make changes permanent for all users we can also append HISTTIMEFORMAT variable to .bashrc_profile. Now execute the following commands in your terminal –
echo 'HISTTIMEFORMAT="%F %T "' >> ~/.bash_profile
And then run the following command to make changes effective –
source ~/.bash_profile
Conclusion
By reading this article now you can display the date and time with the commands displayed when your run history command. If you have any thoughts related to this article please write in the comments below.