Friday, January 23, 2009

Linux command line history with timestamp - HISTTIMEFORMAT


Typically when one type history command, it displays the command number and the command. For auditing purpose, it would be helpful to display the timepstamp along with the command. To do so we need to set the environmental variable HISTTIMEFORMAT.

HISTTIMEFORMAT supports format strings of strftime.

Some important format strings:

%T Replaced by the time ( %H : %M : %S )
%F Equivalent to %Y - %m - %d

Get the full list here

$ export HISTTIMEFORMAT='%F %T '

Now execute

$ history

it will print the command line history with corresponding timestamp when the command was executed.

9 comments:

Caio Moritz Ronchi said...

Great tip, thank you

Damon said...

When I did this it just listed my computers current time for *all* of the history elements:

damon@gaorsk:~$ export HISTTIMEFORMAT="%F %T"
damon@gaorsk:~$ history
5 2009-01-24 08:53:23ssh gaorsk.web
6 2009-01-24 08:53:23s3cmd
7 2009-01-24 08:53:23s3cmd --help
8 2009-01-24 08:53:23nice -h
9 2009-01-24 08:53:23nice --help
10 2009-01-24 08:53:23nice lis
11 2009-01-24 08:53:23nice ls

Any thoughts? Ubuntu 8.6.1

Jadu Saikia said...

@Ronchi, thanks for commenting.

@Damon, Thanks for you comment.

I don't see any problem in your output except a space after %F %T

i.e.

export HISTTIMEFORMAT="%F %T "

Please let me know if you are meaning any other problem.

Jadu Saikia said...

oh!! just noticed, you mean to say you are getting the same time stamp for all the commands ?

I got the problem, the timestamp for command lines that executed in the previous sessions may not valid, as the time was not tracked. Even I see the same thing with my Ubuntu 7.10

Jadu Saikia said...

export this in your .bash_profile, should solve this problem.

Damon said...

That seems to do the trick - thanks ... I wonder if there is any way to "color-ize" it too to make the different columns stand out.

-thanks!

Jadu Saikia said...

So you can have the followings in your .bash_profile:


export HISTTIMEFORMAT='%F %T '

History () {
history | awk -v B=`tput smso` -v N=`tput rmso` '{$1= B $1 N} {$2= B $2 N} {$3= B $3 N} {print}'
}

So that we can use "History" with 1st, 2nd and 3rd col highlighted. Please let me know if have any alternative for this. Thanks.

Damon said...

That did work - cool! There is always so much one can do! I am going to look around with out to play with the color options.

Thanks!

kezesb said...

"Please let me know if have any alternative for this"

Doesn't not color the first column, only the time format, but still it is an alternative:

HISTTIMEFORMAT=`echo -e "\033[1;34m%F \033[1;31m%T \033[0m"`

© Jadu Saikia www.UNIXCL.com