Terminal Incognito Mode

Sometimes you have to run a bunch of commands that you would rather not get saved to your terminal history, such as commands that manage GPG keys, for example. In which case, the following snippet might be useful for you.

Add the following to .zshrc if you use zsh, or .bashrc (or even .bash_profile) if you use bash:

function incognito() {
    unset HISTFILE
    export PROMPT='[INCOGNITO] %n@%m %1~ %# '

You may need to edit PROMPT to say PS1 depending on the terminal you are using. I’ve borrowed the PS1 prompt from the default set on macOS. Edit to your liking and OS defaults if desired.

Now, when you run incognito, the current terminal session will not get saved to the history file. Happy coding!

If you would like an explanation as to how this works, it’s quite simple. Terminals use a history file, such as .bash_history or .zsh_history to record your previous commands so that you can bring them up with the history command or the Ctrl-R keystroke (reverse search through your command history). This is set in the HISTFILE variable, and unsetting it prevents the terminal from finding the history file, which means your current session is not saved.