How to Clear Bash History in Linux and Mac

Clear Bash History.jpg

Sometimes we run bash commands with sensitive information. For example, running a shell script and passing passwords as the command-line arguments. In that case, it’s better to clear the bash history for security reasons.

Clear Bash History in Linux

When we run any command in the bash shell, it gets stored in the .bash_history file located in the user home directory. We can use history command to print all the commands from this file. There are options to delete the entire history or any specific command from the bash history.

1. Delete the Bash History to remove all commands

If you want to remove the bash history completely, you can run the history -c command.

# history
  ...
  737  history
  738  vi .bash_history 
  739  cd
  740  history
# history -c
# history
    1  history
# 
Image 4
Image 4

2. Remove a Specific Command from the Bash History

If you want to remove a specific entry from the bash history, use to history -d offset command. The offset is the line number from the output of the history command.

[root@li1176-230 ~]# ls -1 | wc -l
3
[root@li1176-230 ~]# history
    1  history
    2  ls
    3  cd
    4  ls -1 | wc -l
    5  history
[root@li1176-230 ~]# history -d 4
[root@li1176-230 ~]# history
    1  history
    2  ls
    3  cd
    4  history
    5  history -d 4
    6  history
[root@li1176-230 ~]#
Image 5
Image 5

How to Clear Bash History in Mac OS

If you are using plain bash shell, you can use the -d or -c option to remove the bash history.

bash-3.2$ history
    1  history
    2  cd
    3  ls
    4  pwd
    5  history
bash-3.2$ history -d 4
bash-3.2$ history
    1  history
    2  cd
    3  ls
    4  history
    5  history -d 4
    6  history
bash-3.2$ history -c
bash-3.2$ history
    1  history
bash-3.2$

ZSH Clear History

ZSH is very popular these days. It’s built on top of bash shell and provides a lot of additional features to help developers. Unfortunately, the above history commands won’t work to clear ZSH shell history. It’s because the ZSH history is saved in ~/.zsh_history file. If you want to remove any entry, open this file in VIM or any other editor and manually delete the entry from the file and save it.

Note: The zsh history is loaded when the session starts, so the changes to the .zsh_history file won’t reflect in the current shell session. If you launch a new shell by opening a new window or tab, you will notice the changes.