How do I prevent commands from showing up in Bash history?

Viewed 63103

Sometimes, when I run commands like rm -rf XYZ, I don't want this to be recorded in Bash history, because I might accidentally run the same command again by reverse-i-search. Is there a good way to prevent this from happening?

8 Answers

I added an "Incognito" functionality to my .bashrc for when I want to run some commands without being saved without having to add spaces before each one.

Do note though that the in-memory history of the current terminal session will still be saved, but when I open a new terminal the commands issued in a past terminal's incognito session will never be seen because they were never written to the HISTFILE.

To your .bashrc:

ignoreHistory="false"
DEFAULT_HISTFILE=~/.bash_history
HISTFILE="$DEFAULT_HISTFILE"

# Toggle incognito mode
incognito() {
    if [[ "$ignoreHistory" == "true" ]]; then
        echo -e "\e[33mExited incognito mode\e[39m"
        ignoreHistory="false"
        HISTFILE="$DEFAULT_HISTFILE"
    else
        echo -e "\e[33mEntered incognito mode\e[39m"
        ignoreHistory="true"
        HISTFILE=/dev/null
    fi
}

Nice little utility I think some people may find use in, you can even change the prompt to reflect whether you're in incognito mode or not.

Related