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.
You have to type a command that contains a password or token, and it should not end up in the history file.
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 histvisible-one
hidden-with-leading-space
visible-two
echo visible-one
echo visible-twoWith 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.