Avoid duplicates in your bash history

3 October, 2005 - 15:56
Categories:

Sometimes I need to repeat a command several times on the bash commandline. I don't mean a scenario where you could use a for or while loop, but take for example editing a script in an editor and periodically running it in a terminal. In that case my bash history used to be appended over and over with the same command for running that script.

If you set the shell variable HISTCONTROL to ignoredups, bash will not append a command to the history if it matches the last command of the history.

Add the following to you ~/.bashrc file to enable it (unless it is already enabled, of course):

export HISTCONTROL=ignoredups

In fact, with HISTCONTROL you can do a bit more. The manpage of bash tells the following about HISTCONTROL:
A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ignorespace, lines which begin with a space character are not saved in the history list. A value of ignoredups causes lines matching the previous history entry to not be saved. A value of ignoreboth is shorthand for ignorespace and ignoredups. A value of erasedups causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIGNORE. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL.