Add timestamps to the Bash history

I have to admit that I use my bash history as my personal journal. Of course it will never replace a ‘proper’ documentation, but it is still pretty useful since I can easily find all commands that are relevant for a particular system. Especially regardings some maintenance that you only need to do once in a while it is hard for me to remember the correct syntax without consulting the manuals or some other external documentation.

Theres one drawback though: By default, the bash history helps you finding the command itself, but not when it was issued for the last time. A quick modification in the bash profile resolves this issue.

The magic word we need is HISTTIMEFORMAT. This variable controls whether, and if so in which format, the date and/or time will be stored in the bash history. As usual this variable has to be set in the .bashrc (or .bash_profile) file. You can use the same format as expressed by the date command. Since the timestamps are kept as Unix timestamps in the bash history, you can easily modify the format at a later point in time. All changes will be retroactively applied.

For my new default configuration, I started to use the following entry:

HISTTIMEFORMAT="%Y-%m-%d %X %z "

Afterwards, the output of my history looks as follows:

2021-11-28 17:10:21 +0100 echo "Das ist ein Test-Eintrag für den Blog!"

By the way: Executing commands with !line_number will continue to work since the timestamps are not interpreted by the shell itself.

Leave a Reply

Your email address will not be published. Required fields are marked *