Shell history timestamps

Tips for HP-UX sysadmins

Shell history timestamps

The shell history is very useful  except for one item: a timestamp. This is especially important for root user logins but also for DBAs and web maintenance workers. Fortunately there is an easy way to add a timestamp to every command using trapand read. For HP-UX, the POSIX shell, Korn shell and Bourne shell have a -s option for read that takes stdin and writes it to the history file. To add a time stamp:

date | read -s

This will silently add the date (or any string or command output) to the shell history file.

To make this happen for each command that is given to the shell, you can use trap with the debug signal. When the debug signal is assigned to trap, every command issued to the shell will run the trap argument.

By combining read and trap, the date can be added to every command like this:

trap ‘date “+ # %a %Y-%m-%d.%H%M%S” | read -s’ debug

When this command is issued at the shell prompt, each command in the shell history will be followed by the date. The + options to the date control the appearance of the date components. Feel free to change them as needed. The # sign prevents trying to run the line if it is recalled. You can turn off the timestamps at any time like this:

trap ” debug

Note that the shell history may become too cluttered with a time stamp on each command. Rather than every command, you can add this to your login profile:

echo “#ttt$(date)” | read -s

Now, a single timestamp will occur for each login. To prevent trying to access the history file when a login is in batch mode, use tty to filter out batch operations, like this:

# Add timestamp to every .sh_history command

if tty -s

then

   trap ‘date “+ # %a %Y%m%d.%H%M%S” | read -s’ debug

fi

or

# Add timestamp to .sh_history at login

if tty -s

then

  date “+   ## login: %a %m/%d/%Y @ %H:%M:%S” | read -s

fi

Just add one of the choices above to your .profile.

This assumes you are using /usr/bin/sh or /sbin/sh or /usr/bin/ksh as your login shell.

– See more at: http://serviceitdirect.com/blog/shell-history-timestamps#sthash.M3eBix8c.dpuf