Skip to content

Persistent bash history > An experiment

Since I am an avid Linux user, I like to spend a lot of time in the terminal. Open a terminal, type a command, open another one, do another thing…this is my routine. Often you need to retype the same commands, so the bash history is vital for productivity. Unfortunately, I have never understood how history between different terminal windows works. The “right” history seems to be always missing.

Lately I found a few interesting programming blogs and read through a lot of posts. One post was really creative and proposes to use a persistent history file, where every command ever typed into a terminal is saved.

Here is the code, which goes into the ~/.bashrc file in your home directory.

### persistent history

    $(history 1) =~ ^\ *[0-9]+\ +([^\ ]+\ [^\ ]+)\ +(.*)$
    local date_part="${BASH_REMATCH[1]}"
    local command_part="${BASH_REMATCH[2]}"
    if [ "$command_part" != "$PERSISTENT_HISTORY_LAST" ]
        echo $date_part "|" "$command_part" >> ~/.persistent_history
        export PERSISTENT_HISTORY_LAST="$command_part"

# Stuff to do on PROMPT_COMMAND


You can either reboot or input the following command to reload the .bashrc file:
source ~/.bashrc

This creates a .persistent_history file which looks like this:

29/04/16 20:57:42 | cat .persistent_history
29/04/16 20:57:46 | git status
29/04/16 20:57:48 | cat .persistent_history
29/04/16 21:15:02 | vim .bashrc

Now you can just use it and let it work in the background. Or you can add more functions to it, like loading the last 100 entries into your current history. I will use it for a few months and report back

Published inTips and Tricks

One Comment

Leave a Reply

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