Making my bash history more informative

I’m a long time bash user and have found that I really want more information in my bash history file … more than just the typical command number and command line. So, to my .bashrc I’ve added a time stamp, process id, and tty to the history output by setting HISTTIMEFORMAT like so

export HISTTIMEFORMAT="%F %T %Z %z $$ $TTY "

which produces something like

957 2022-03-02 10:37:05 PST -0800 684 /dev/pts/0 history | tail

As you can see, this adds, after the command number, the date as YYYY-MM-DD, the time with timezone and GMT offset, the process id and the tty on which it was entered. I also like to keep track of the commands that are entered when I’m in a certain directory (useful for git and, well, all sorts of things) so I add

$PWD "$(history 1)" >> ~/.history/$(basename $PWD)'

This appends a history line to a directory in ~/.history which corresponds to the last component of the directory in which the command was entered. So, if my current working directory is ~/dev/git, commands are also appended to ~/.history/git along with the tty on which they were entered, the current process id, the current user and the full working directory which gives me something like

/dev/pts/1 1806 user /home/user/git 951 2022-03-02 10:47:00 PST -0800 1806 /dev/pts/1 ls -l ~/.history

Note, I don’t change HISTFILE so everything is still in one history file. And I use an alias to show history for the current directory

alias cathist='cat ~/.history/$(basename $PWD)'

And, while I’m at it, I enable host name completion with shopt -s hostcomplete and also ask bash to try to save a multiline command in one history entry with shopt -s cmdhist. And if I have lots of space, I allow my history file to grow as large as needed by setting (or unsetting) HISTFILESIZE and HISTSIZE. So I end up with the following lines added to my .bashrc

export HISTSIZE=
shopt -s histappend
shopt -s cmdhist
shopt -s hostcomplete

export HISTTIMEFORMAT="%F %T %Z %z $$ $TTY "

$PWD "$(history 1)" >> ~/.history/$(basename $PWD)'

alias cathist='cat ~/.history/$(basename $PWD)

I picked this up from various sources and modified it to fit my needs. Feel free to use or hack as you see fit.

Making my bash history more informative Read More »