bash history and reverse history search March 31st, 2008


Spending a lot of time in linux means that you may type the same command twice or more. Using the bash history can save you a lot of re-typing. I typically only use one feature of history search known as 'reverse history search'. You can activate this mode by pressing CTRL-R at the bash prompt and then typing a substring of the command you want.

However, the default options for bash history don't do it any justice. By default it will only save the history when you exit from a terminal, the history is overwritten each time the save happens and is set to a small history size. To remedy all these things you can put the following in ~/.bashrc


export HISTCONTROL=ignoreboth
export HISTSIZE=1000000 HISTFILESIZE=1000000
export HISTFILE=~/.bash_history_safe
export PROMPT_COMMAND='history -a; history -n'
shopt -s histappend

Also, if your .bashrc file is already using PROMPT_COMMAND for other features then you must edit the PROMPT_COMMAND string and add '; history -a; history -n' to the end. For example, my .bashrc file was changed to the following:

# If this is an xterm set the title to user@host:dir
case "$TERM" in
xterm*|rxvt*)
    PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD/$HOME/~}\007"; history -a; history -n'
    ;;
*)
    ;;
esac