You can only edit, delete, or publish your own posts.

July 30, 2020, 6:54 p.m.

How to effectively clean bash history when closing the terminal

by: mc



Why don’t mermaids use Bash? Because they prefer a C-Shell. (anonymous)

If you are serious about security on your Linux server(s), you will want the bash/shell history to be cleared when a user closes all the terminals she/he's been using.

Let's see how to do it effectively.

The basic command to clear bash history completely is history -c. However, history entries have a copy in the memory that will be saved in the .bash_history file as soon you exit the terminal.

To clean the .bash_history file, the user will have to type another command after history -c - and here there are some options:
a) The purists will advise to "send the data to the void", cat /dev/null > ~/.bash_history; the concatenated command to write will then be history -c && cat /dev/null > ~/.bash_history(1);
b) There's a way to shorten the second command by truncating(2) the .bash_history file; the full line command being now history -c && > ~/.bash_history;
c) That's better, but it's possible to do the same with a shorter line, history -c && history -w(3).

Okay, now that you have the most efficacious command how shall you use it?

Also here there are some options:
a) The purists will recommend the use of a cron job. However, if the user's terminal is still open after the scheduled hour for clearing, all history will be kept in the .bash_history file to the next day.(4)
b) To assure that all history will be cleared, and kept clear, when the user closes her/his terminal window(s), edit the file .bashrc and write the following two lines at the end of it:

# delete history when the terminal is closed
history -c && history -w

(5)

Save and test it. :)


(1) /dev/null in Linux is a null device file. It will discard anything written to it, and will return EOF on reading. This is a command-line hack that acts as a vacuum and sucks anything thrown to it. Other names for /dev/null are bit-bucket, black hole, null route, punch bucket, null device, or just null.
(2) Simply using the redirection operator with no command preceding it will truncate an existing file or create a new empty file.
(3) And if you have two options that do the same, you should of course choose the simpler one.
(4) For example, if you want to clear the history of user1 at 11:30 p.m. every day: Open a terminal and type sequentially su - user1, crontab -e; This will open the crontab editor for user1; Enter 30 23 * * * history -c && history -w; save the file.
(5) Contrarily to what some people say, it's no use to write this commands on the file .bash_logout.

No comments here yet :(