Bash History Fun!

Mon 11 October 2010

If you're one to have lots of terminals open at once, and ALSO have a mind like a steel sieve, it's nice to have more information from the bash history command and \~/.bash_history file. Here are several ways to increase their power:

  1. Timestamps

    By setting a bash environment variable, you can easily enable timestamping on each and every command you run. The HISTTIMEFORMAT variable works like the `date` command or strftime() if you're familiar with that syntax:

    export HISTTIMEFORMAT="%Y/%m/%d - %H:%M:%S "

    In this case, the timestamps will look like: 111 2010/01/16 - 11:01:52 du -mx | sort -n | tail
    Restart bash after adding this to your \~/.bashrc to see the difference. Notice that old entries will get timestamped with the time they were read in as they had no timestamp data before. Also, \~/.bash_history contains the timestamps in Unix time (seconds since Jan 1, 1970) so changing your HISTTIMEFORMAT in the future will display the new timestamps how you want.

  2. Multi-terminal history

    Usually, when you close a bash shell, it overwrites the existing \~/.bash_history. This can be bad when you open lots of terminal windows at once. Whichever one you close last ends up writing out the history file. That's no good! To fix this, you need to tell bash to append history, not overwrite:

    shopt -s histappend
    

    The biggest thing to note here is that your \~/.bash_history file will now be out of chronological order. Because of this, I recommend enabling timestamps FIRST, as you'll need them to sort out the timestamps. To take the `history` command and resort it chronologically, use

    history | sort  -k 1.8,1.11n -k 1.13,1.14n -k1.16,1.17n -k 1.21,1.22n -k 1.24,1.25n -k1.27,1.28n
    

    Adding this as an alias like "chistory" would probably make it a lot easier to use.

  3. Eternal History

    This tip is from http://www.debian-administration.org/articles/543 and shows a method where you can use the PROMPT_COMMAND variable to write out your last history record to a file called \~/.bash_eternal_history. So long as you have the space for it, it works very well! 4. Going Heavy Duty

    What if you want to log ALL commands by ALL users? That's where things like snoopy or Configuring auditd to track command execution system-wide. If you're going to implement something like this, be warned that the amount of log data you'll generate will be immense.

Category: shell Tagged: bash history scripting shell

comments