How to show date and time in your history command using environment variable HISTTIMEFORMAT

It usually happens with me that I am trying out a cli based tool or learnt some new trick, it works fine then, but later I can hardly recall what I did . In such cases, all I remember is either a part of the command or the time while I was doing it. I always wondered if we could get more out of the history command - days, time etc. After searching a little, I found that it is actually possible and could be done pretty easily.

Its all in the genius of Bash . All you have to do is set the environment variable, HISTTIMEFORMAT, appropriately. Lets take an example where I just want to so the timestamp.

[shredder12]$ export HISTTIMEFORMAT="%T "
[shredder12]$ history
568  13:53:01 clear
569  13:53:03 top
570  13:53:07 sudo fdisk -l
571  13:53:16 free -m
572  13:53:17 cd
573  13:53:18 ls
574  13:53:22 cd Downloads/

Similary, for date you can use the following parameters

%d for Day
%m for Month
%y for Year

So, if you want both date and timestamp

[shredder12]$ export HISTTIMEFORMAT="%d/%m/%y %T "
[shredder12]$ history

568  25/10/10 13:53:01 clear
569  25/10/10 13:53:03 top
570  25/10/10 13:53:07 sudo fdisk -l
571  25/10/10 13:53:16 free -m
572  25/10/10 13:53:17 cd
573  25/10/10 13:53:18 ls
574  25/10/10 13:53:22 cd Downloads/

Please note that, for a permanent setting you will have to append the "export" line in ~/.bashrc file.

1 Comment

John McGehee (not verified)
October 26th, 2010 04:10 am
Great tip. For better sort-ability, I used year/month/day:
export HISTTIMEFORMAT="%y/%m/%d %T "
but watch out for Y2K ;-).

Also note that the shredder12 is using the order customary in Europe, %d/%m. Americans may want to reverse this to %m/%d.

Further amusing question: is there an environment variable that contains the customary date format for the current locale? If it exists, you could use it in the definition of HISTTIMEFORMAT.

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <img> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <blockquote> <h1> <h2> <h3> <h4> <h5> <h6> <p> <br>
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • Image links with 'rel="lightbox"' in the <a> tag will appear in a Lightbox when clicked on.
  • Search Engines will index and follow ONLY links to allowed domains.

More information about formatting options

Type the characters you see in this picture. (verify using audio)
Type the characters you see in the picture above; if you can't read them, submit the form and a new image will be generated. Not case sensitive.