你能阻止命令进入 bash shell 命令历史吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/640403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 20:45:12  来源:igfitidea点击:

Can you prevent a command from going into the bash shell command history?

linuxbashunixshell

提问by KarstenF

Is there a way to prevent a command from being added to the bash shell's command history?

有没有办法防止将命令添加到 bash shell 的命令历史记录中?

I would like to be able to prevent certain "dangerous" commands from being added to the history, such as "rm -rf ~/some/dir", so that it is not accessible to me by pressing the up-arrow to reach previous commands. In this way, it would not be possible to accidentally repeat one of these commands.

我希望能够阻止某些“危险”命令被添加到历史记录中,例如“ rm -rf ~/some/dir”,这样我就无法通过按向上箭头来访问以前的命令来访问它。这样,就不可能意外地重复这些命令之一。

The reason I ask is that I use the up arrow a lot to access previous commands in the shell history, and have often caught myself about to hit enter on what I thoughtwas the correct command, only to realise that I was about to do something stupid/annoying/dangerous. I don't like the idea of rms etc floating around in my shell history, waiting for me to step on them!

我问的原因是我经常使用向上箭头来访问 shell 历史记录中的先前命令,并且经常发现自己正要按我认为是正确的命令的Enter 键,才意识到我将要执行某些操作愚蠢/烦人/危险。我不喜欢rms 等的想法在我的 shell 历史中四处飘荡,等着我去踩它们!

(Note: I am aware that one can set up patterns in HISTIGNORE, but what would be nice is something one can apply on a per-command basis, which would become good a habit. Unless there is a clever way to achieve this using HISTIGNORE that I have missed?)

(注意:我知道可以在 HISTIGNORE 中设置模式,但最好是可以在每个命令的基础上应用一些东西,这将成为一种好习惯。除非有一种聪明的方法可以使用 HISTIGNORE 来实现这一点我错过了?)

回答by Node

On newer Bash Versions you could simply add a space at the beginning of your command. :) If it doesn't work by default, add [ \t]* to HISTIGNORE. (As mentioned in the comments. thx)

在较新的 Bash 版本上,您只需在命令开头添加一个空格即可。:) 如果默认情况下它不起作用,请将 [ \t]* 添加到 HISTIGNORE。(如评论中所述。谢谢)

回答by T-Hawk

Add ignorespaceto your HISTCONTROLenvironment variable. Then any command line that begins with a space won't be entered into your history.

ignorespace添加到您的HISTCONTROL环境变量。那么任何以空格开头的命令行都不会输入到您的历史记录中。