history -a vs -w in BASH. How to replace/append and ignore/erase duplicates?

You stated two questions:

What is the difference between history -a and history -w?

history -a will append your current session history to the content of the history file.

history -w will replace the content of the history file with your current session history.

Which one avoids more duplicates?

Theoretically neither. Neither -a nor -w checks for duplicates. You can argue that -w avoids more duplicates but only because it removes the previous content of the history file. So any potential duplicate entries in the file are eliminated. Along with anything else in the file.


Background information:

Bash has a history feature. In most distros bash is configured to have history enabled by default.

For the most basic use cases it works as follows: all commands typed in the prompt and executed will be put in history. If you press the up arrow on an empty prompt it will recall the last command entered. Press up again and it will recall the second to last command.

If you want more advanced features, like duplicate avoidance, you will first need to understand the following: in any bash session there are at least two versions of history. One is the history that is stored in the memory of the currently running bash process (the session history). The other is the history saved on disk (the history file).

When using bash and using the history feature in bash you typically only work with the session history. the history file is only touched on certain events. such events are for example: bash startup, bash shutdown, or invocation of history -a or history -w.

A common bash configuration is as follows: on bash startup read from history file to session history. While running and executing commands from prompt only manipulate the session history. on shutdown replace content of history file with session history.

Bash has features to avoid some duplicates in the session history. But none (that i know of) in the history file.


Bash features to avoid some duplicates:

set the special bash variable HISTCONTROL to ignoredups. effect is if you reexecute the same command immediately again the duplicate will not be saved to session history. But if you reexecute a command from history after executing other commands in between the duplicate will still be saved to session history.

set the special bash variable HISTCONTROL to erasedups. effect is erase any existing history entry matching the currently entered command. but note it only does so in the current session history. It does not search for duplicates in the history file. It will also not prevent duplicates from entering your session history when using history -n (read entries from history file to session history).


more details in the bash manual:

about the history command.

about the special variable HISTCONTROL.