如何在 bash 中运行命令而不将其保存在历史记录中?
答案1
在命令前添加空格。以空格开头的命令不会记入历史记录:
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.
答案2
另外值得一提的是,有一个技巧可以终止当前登录会话,而不是正常退出(这样就不会有机会保存历史记录)。这在您登录共享帐户时特别有用,您无需记住在前面加上空格,只需终止会话即可结束会话。最简单的终止方法是运行以下命令:
kill -9 0
Pid 0 始终指当前进程的 PID,因此您基本上是在向其自身发送致命的终止信号。我还经常使用此方法而不是正常退出,因为我经常在正常退出时挂起会话,这可能是由于某些配置错误造成的。
答案3
另一个解决方案是将历史文件设置到目录:
export HISTFILE=/
答案4
接受的答案在非 Ubuntu 版本的 bash 中确实有效,但根据手册页,必须在环境变量中设置ignorespace
或值。在 macOS 上,此变量默认为空,并且此功能不起作用,但运行后,它现在会忽略以空格为前缀的命令,如所述。ignoreboth
HISTCONTROL
export HISTCONTROL=ignorespace