show commands with date & time in Linux history

Linux History: Show Commands with Date & Time

Linux history allows you to show past commands executed in terminal session. However, it does not show the date & time of execution. Sometimes you may need to display commands with date & time in Linux. It helps you search for commands executed on a specific date & time. In this article we will look at how to show commands with date & time.

Linux History: Show Commands with Date & Time

Here are the steps to show commands with date & time. By default, history shows only command number and executed command.

Here is the default output of history.

$ history
  1994  sudo systemctl status apache2
  1995  ls
  1996  cd /var/www/html/
  1997  ls
  1998  cd tech-blog/
  1999  ls
  2000  sudo vim .htaccess

The above history command does not display the date/time at which these commands were executed.

Also read : How to Limit Requests Per IP in Apache

In order to show commands with date & time, we will create an environment variable HISTTIMEFORMAT and add it to bash shell with the following command.

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

In the above command, we have used certain format specifiers to describe the timestamp format for commands.

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

You can change them as per your requirement. Whenever you run history command, it looks for the HISTTIMEFORMAT variable to determine the date & time format of displayed commands.

Also read : How to Change XAMPP Apache port

Apply the changes using the following command.

$ . ~/.bash_profile
$ source ~/.bash_profile

Now when you run the history command, it will show the commands with date & time.

$ history
  1994  20/04/21 04:15:32 sudo systemctl status apache2
  1995  20/04/21 04:15:32 ls
  1996  20/04/21 04:15:32 cd /var/www/html/
  1997  20/04/21 04:15:32 ls
  1998  20/04/21 04:15:32 cd tech-blog/
  1999  20/04/21 04:15:32 ls
  2000  20/04/21 04:15:32 sudo vim .htaccess

This is useful because if you want to search for commands executed at a particular date & time, just pass the output of history command to grep command. Here is an example,

$ history | grep "20/04/21 04:23"
  2002  20/04/21 04:23:28 echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bash_profile
  2005  20/04/21 04:29:36 history | grep "20/04/21 04:23"

Also read : How to Use Linux History Command

Leave a Reply

Your email address will not be published. Required fields are marked *