Terminal Incognito Mode

Warning: This post is over 365 days old. The information may be out of date.

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.


If you have Powerlevel10k (a ZSH theme) installed like I do, the prompt customization with export PROMPT won’t work. Thankfully, the theme is awesome, and it lets you define custom segments to put on your prompt bar.

Edit ~/.p10k.zsh and add the following to the end:

# Custom incognito segment
function prompt_is_incognito_mode() {
    if (( ! ${+HISTFILE} )); then
        p10k segment -f red -i '🥷'

Then find the part that defines POWERLEVEL9K_LEFT_PROMPT_ELEMENTS and add is_incognito_mode to the front (or anywhere you prefer):

  # The list of segments shown on the left. Fill it with the most important segments.
    # Incognito mode indicator
    # =========================[ Line #1 ]=========================
    # os_icon               # os identifier
    dir                     # current directory
    vcs                     # git status
    # =========================[ Line #2 ]=========================
    newline                 # \n
    prompt_char             # prompt symbol

Also, you can change the incognito function in ~/.zshrc like this:

# Function for "incognito" mode
function incognito() {
    unset HISTFILE
    echo "Done! This terminal session will not be recorded into history."

Now, when you run incognito, you’ll be greeted by this cute little ninja:

> incognito
Done! This terminal session will not be recorded into history.

 🥷  | ~