Get timestamps in Bash history

Although history command utility in Linux is already nice, it would have been great if we can have timestamp to understand when certain commands were run. This is particularly useful for organizations, that needs to match certain audit requirements. We can easily configure timestamps by using HISTTIMEFORMAT environmental variable in following way:

HISTTIMEFORMAT="%d/%m/%y %T "  # for e.g. "13/03/21 15:59:59"
HISTTIMEFORMAT="%F %T "        # for e.g. "2021-03-13 15:59:59"

However to make our changes persistent across system reboots, we need to modify bash profile for current user, .bashrc:

echo 'HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bashrc # for e.g. "13/03/21 15:59:59"
echo 'HISTTIMEFORMAT="%F %T "' >> ~/.bashrc       # for e.g. "2021-03-13 15:59:59"
source ~/.bashrc # reload profile

Do note that for commands that were run before HISTTIMEFORMAT was set, the current time will be saved as the timestamp. Commands run after HISTTIMEFORMAT was set will have the proper timestamp saved.

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 )

Facebook photo

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

Connecting to %s