On your Linux machines, a history of your bash commands is retained. This is great when you need to repeat a command or can’t remember exactly how you executed a command in a previous session. However, this can also be seen as a security issue. What if someone gains access to your machine, opens a terminal window, and checks through your bash history to see what commands you’ve run?
Bash has a handy way to clear the history: issue the command history -c. There’s a slight problem with that approach. Let me explain.
First off, your bash history is retained in the file ~/.bash_history. When you have a terminal open, and you issue a command, it writes the command to the history file. So issuing history -c will clear the history from that file. The problem comes about when you have multiple terminal windows open.
Say you have two terminal windows open and you issue history -c from the first one and close that window. You then move to the second terminal window, and you type the exit command to close that window. Because you had a second bash window open, even after running the history -c command in the first, that history will be retained. In other words, the history -c command only works when it is issued from the last remaining terminal window.
How do you get around that? You empty the .bash_history file either on a per-instance basis or by using a crontab job to do it regularly. If security is a serious matter for you, consider setting up the crontab job. Here’s how.
SEE: Linux Foundation launches badge program to boost open source security (ZDNet)
Clearing bash history on a regular basis
Before I show how to set up the crontab job for this, know that the ~/.bash_history file can be cleared with the command:
cat /dev/null > ~/.bash_history
That will empty out the contents of the file, but keep the file in place.
Let’s say you want to clear the .bash_history file for user olivia (who administers your Linux server) at 11:00 p.m. every day. You would create a cron job under the olivia account. To do that, log in as the user olivia, open a terminal window, and issue the command crontab -e. When the crontab editor opens, enter the following:
00 23 * * * cat /dev/null > ~/.bash_history
Save that file and cron will start clearing out olivia’s history at 11:00 p.m. every day.
A surefire method
This is a surefire method of clearing out your bash history. Don’t always rely on the history -c command, because you never know when a second (or a third) terminal is still open, ready to keep that history retained.