How to run command in bash without saving it in history?
Add space before command. commands starting with a space do not put in history:
root@ubuntu-1010-server-01:~# echo foo foo root@ubuntu-1010-server-01:~# history 1 echo foo 2 history root@ubuntu-1010-server-01:~# echo bar bar root@ubuntu-1010-server-01:~# history 1 echo foo 2 history
HISTCONTROL A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes ignorespace, lines which begin with a space character are not saved in the history list. A value of ignoredups causes lines matching the previous history entry to not be saved. A value of ignoreboth is shorthand for ignorespace and ignoredups. A value of erasedups causes all previous lines matching the cur‐ rent line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If HISTCONTROL is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of HISTIGNORE. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of HISTCONTROL.
Also worth mentioning the trick to kill the current login session instead of normal exit (thus not giving a chance to save the history). This is especially useful when you login to a shared a/c, instead of remembering to prefix with a space, you could just end the session by killing it. The simplest way to kill is by running this command:
kill -9 0
Pid 0 always refers to the current process's PID, so you are basically sending a deadly kill signal to itself. I also often use this instead of exiting normally, as I often have hung sessions on normal exit, probably due to some misconfiguration.
The accepted answer does work in non-Ubuntu versions of bash, but per the man page the
ignoreboth value must be set in the
HISTCONTROL environment variable. On macOS this variable is empty by default and this feature doesn't work but after running
export HISTCONTROL=ignorespace it now ignores commands run prefixed with a space as described.