Bash – How to stop Bash appending history

bashcommand history

I am having a lot of trouble setting up the terminal history of Bash the way I want. I would like to have no duplicate entries and if I enter a command I want it saved and the duplicates above removed.

The problem is the history command shows me it is functioning the way I want, but once I log out the duplicates come back again. I believe it is just appending the history to the existing one. I have these lines in my .bashrc file:

HISTCONTROL=ignoreboth:erasedups
shopt -u histappend

I have even tried uncommenting shopt, but it still appends the history on logout. How can I have the history be exactly how it is before I logout?

Best Answer

The erasedups should do what you want in regard to the duplicates - just note that erasing duplicates is triggered at the moment of appending a new entry to the history and that it erases all the old occurrences of a command, leaving just the most recent.


Answering the question "How can I have the history be exactly how it is before I logout?"

The way I see it, this can be useful only once in a while. (Otherwise why would you use history at all?) You can do it by issuing

history -c; history -r

This clears all the history entries kept currently in memory and then re-reads the whole history from the history-file. So all the commands you issued since logging into the current shell session are forgotten. I find it quite useful in situations when I do a lot of testing (many similar commands, but not really duplicates) and then don't want to have my history garbaged by that - so I have an alias for it in my .bashrc:

alias hrr='history -c; history -r'

(hrr to be remembered as "history re-read").