Skip to content
shellhacks.dev
Security

Keep Secrets Out of Bash History with a Leading Space

Keep a command with a secret out of Bash history by starting it with a space and setting HISTCONTROL=ignorespace. It only applies to interactive Bash.

1 min read
Summarize in AI

You have to type a command that contains a password or token, and it should not end up in the history file.

Shell
export HISTFILE=$PWD/hist HISTCONTROL=ignorespace
bash -i 2> /dev/null <<'EOF'
echo visible-one
 echo hidden-with-leading-space
echo visible-two
EOF
cat hist
Text
visible-one
hidden-with-leading-space
visible-two
echo visible-one
echo visible-two

With HISTCONTROL=ignorespace the shell does not save a line that begins with a space. The run starts an interactive Bash on three commands and the history file holds only echo visible-one and echo visible-two, while the one with the leading space was never written. ignoredups and ignoreboth are the related values. See HISTCONTROL in Bash Variables.

This is a convenience and not a security control. The command is still visible in the process list while it runs, in the terminal scrollback and in the shell's memory until it exits. Better yet, read secrets from a file or a prompt so they are never typed on a command line. Some distributions set ignoreboth already, and zsh uses HIST_IGNORE_SPACE.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.