17

Tip #180   Permanent bash history

Often I find myself using Ctrl-R in Bash to get an old command, only to find that too many days have passed and it's no longer in the .bash_history file.

It is possible to increase the number of lines in the history file, but there can always be a moment when you'll need a long command from many months ago. The solution below uses the PROMPT_COMMAND variable, a command that bash executes before showing each prompt. Here are the two lines to add to your profile:

export HISTTIMEFORMAT="%s "

PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND ; }"'echo $$ $USER \ "$(history 1)" >> ~/.bash_permanent_history'


If a previous PROMPT_COMMAND was set, it gets executed before this and then appends a line of the format:

PID USER INDEX TIMESTAMP COMMAND

to a file called .bash_permanent_history in the current user home.

Adding the username is useful to distinguish between "sudo -s" sessions and normal sessions which retain the same value for "~/", and so append lines to the same .bash_permanent_history file.