🐧 How to clear bash history on logout

How to automatically clear the GNU Bourne-Again SHell history when exiting the shell?

Disable the HISTFILE shell variable at login to prevent command history from being saved when you exit the shell.

$ echo "unset HISTFILE" | sudo tee /etc/profile.d/unset_histfile.sh

Optionally, set the HISTSIZE shell variable to 0 at logon so that commands executed are not stored in the history list.

Attention, this is very inconvenient, as it will completely disable the history in the login shell.

$ echo "HISTSIZE=0" | sudo tee /etc/profile.d/disable_histsize.sh

Create a /etc/bash.bash_logout file to execute when the shell exits.

Use it to clear history.

Don’t worry, it will be executed after a separate login shell cleanup file ~ / .bash_logout.

$ echo "history -c" | sudo tee /etc/bash.bash_logout

Note, it will not write an empty history list to the history file. Adding a second command to write the history list to the history file will not work since the HISTFILE shell variable has not been set. This also means that the history list will not be initialized from the history file on startup. Delete the existing ~ /.bash_history file to keep everything in order.

But be aware of other users.

You can always save the history list to a special file.

Note that this will add the current history list to the file.

$ HISTFILE=session_history.txt history -w
$ cat session_history.txt
cat .bash_history
HISTFILE=session_history.txt history -w
Sidebar