X

How to clear Bash history on Linux

The bash history is a log file that contains all commands that a user executed on the Linux BASH shell. When you use the "arrow up" key on your keyboard, then Bash will look up the previous command from that file and display it on the screen. You just have to press "Enter" to execute it again.

Bash history file location

The .bash_history file is in the home directory of the user. When your username is "tom", then the .bash_history file is in the path:

/home/tom/.bash_history

Or a more general path is:

~/.bash_history

as ~ points always to the home directory of the currently logged-in user.

View Bash History

You can use any text editor to view the bash history or use the commands cat and tail.

To view the full bash history, use the command:

cat ~/.bash_history

To view the last 100 commands, use:

tail -n 100 ~/.bash_history

Why clean up the history file?

Sometimes you might want to clean the file to prevent that another user that uses the same account (or the admin user of the server) can look up the commands that were executed. E.g. you used a shell command that contained a password in cleartext and you don't want that someone is able to look this password up. Another scenario is that you are building a clean virtual machine image to share it with others and you don't want that everyone can see all commands that you executed to build that VM image.

Clear the Bash history

Run the commands:

history -w
history -c

To clear the history file.

Finally, you should check if history clearing has worked, press the "arrow up" key on your keyboard, if it does not show the past commands (except for the history cleaning command) then the procedure was successful.

Another way to clean the history file is this command sequence:

cat /dev/null > ~/.bash_history && history -c && exit

It will clear the history and end the current user session. Be aware that this command will kick you off the shell.

Remove a single command from Bash history

In case you just want to remove a single command or a few commands from bash history, you can edit the file with a text editor. I will use the nano editor in this example:

nano ~/.bash_history

Remove the lines that you want to get rid of by deleting them in the text editor, then save the file.

How to prevent that Bash history is written

If you know up front that you don't want to save the command history to the history file, then you can prevent that the .bash_history gets saved with this command:

unset HISTFILE

This command removes the HISTFILE Shell variable which contains the number of records that shall be saved in the history.

If you like to get this behavior on each login, then add "unset HISTFILE" in the .bashrc file of your user:

echo "unset HISTFILE" >> ~/.bashrc
Tags: bashShell
Till Brehm:
X

Headline

You can control the ways in which we improve and personalize your experience. Please choose whether you wish to allow the following:

Privacy Settings