Home > bash > bash – Add time and date to history log

bash – Add time and date to history log

Problem:

Had a situation at work where it is *alleged* that a cron job ran twice. We checked the crontab logs in /var/log/messages but the said cron job was only recorded once. Looking at the bash history we noticed that the affected script was run on the command line, but unfortunately, we could not tell *when* it was run. Which forced us to add timestamps to the history file. If only we had done that earlier. Hopefully, this will be able to shed some light in case it happens again. Only down side to this is that the old commands in the history file get that days timestamp.

Solution:
Add the following line to your users .bash_profile or to .bashrc

export HISTTIMEFORMAT=’%Y-%m-%d %H:%M:%S ‘

shell> source .bash_profile

Before:

  152 history | less
  153 less .bashrc
  154 exit

After:

  155  2011-06-13 11:13:11 mount /dev/sda2
  156  2011-06-13 11:13:11 history | less
  157  2011-06-13 11:13:11 vim .bash_profile
  158  2011-06-13 11:13:11 source .bash_profile 
  159  2011-06-13 12:08:43 history | less
  160  2011-06-13 12:09:05 exit

Formats used:

%Y year
%m month (01..12)
%d day of month (e.g, 01)
%H hour (00..23)
%M minute (00..59)
%S second (00..60)

For other formats read man date

Advertisements
Categories: bash Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: