Bash - Clear History Upon Exiting Terminal

Cleaning terminal history

Whether you want to have some sense of privacy or a sense of cleanliness, working with the terminal leaves a history that you might want to remove.

Removing the .bash_history upon exiting the terminal is the goal for this post.

Create a .rm_terminal_history.sh file in the directory that .bashrc file is in.

.rm_terminal_history.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
rm_hist(){  
if [ -f ~/.bash_history ]
then
rm ~/.bash_history
history -c
echo ".bash_history removed."
exit 0
else
echo ".bash_history can not be found."
exit 1
fi
}

trap rm_hist EXIT

After the script is created, give it executable privileges.

Make Script Executable
1
chmod +x .rm_terminal_history.sh

Now add a reference to your .bashrc file for the script to run

Add Entry to .bashrc
1
2
#Add following line to .bashrc
source ~/.rm_terminal_history.sh

The .bash_history file will be remove when exiting the terminal at any time.