在进行软件开发时,经常需要在命令行命令中包含机密信息。典型的例子是设置将项目部署到服务器作为环境变量的凭据。

当我不想将某些命令存储在命令历史记录中时,如何执行它们?

必须没有人能够在.bash_history文件中搜索它们。是否有一种方法可以这样执行Bash命令?


当前回答

如果你正在使用Z shell (zsh),你可以运行:

setopt histignorespace

设置后,以空格开头的命令将从历史记录中排除。

你可以在.zshrc中使用别名来打开/关闭:

# Toggle ignore-space. Useful when entering passwords.
alias history-ignore-space-on='\
setopt hist_ignore_space;\
echo "Commands starting with space are now EXCLUDED from history."'

alias history-ignore-space-off='\
unsetopt hist_ignore_space;\
echo "Commands starting with space are now ADDED to history."'

其他回答

如果你正在使用Z shell (zsh),你可以运行:

setopt histignorespace

设置后,以空格开头的命令将从历史记录中排除。

你可以在.zshrc中使用别名来打开/关闭:

# Toggle ignore-space. Useful when entering passwords.
alias history-ignore-space-on='\
setopt hist_ignore_space;\
echo "Commands starting with space are now EXCLUDED from history."'

alias history-ignore-space-off='\
unsetopt hist_ignore_space;\
echo "Commands starting with space are now ADDED to history."'

以空格开始命令,它将不会包含在历史记录中。

注意,这需要设置环境变量$HISTCONTROL。

检查以下命令是否返回ignorespace或 ignoreboth: echo $ HISTCONTROL 如果缺少环境变量,可以将下面的行添加到Bash概要文件中。例如,文件%HOME/.bashrc。 出口HISTCONTROL = ignorespace

在再次获取概要文件之后,以空格为前缀的命令将不会被写入$HISTFILE。

还可以使用以下命令:

echo toto; history -d $(history | sed -n '$s/\s*\([0-9]*\)\s*.*$/\1/p')

我认为这是一个非常方便的命令。

如果您想删除所有历史记录,包括删除所有历史记录的事实,这是很方便的!

rm .bash_history;export HISTFILE=/dev/null;exit

正如Doodad在评论中提到的,unset HISTFILE可以很好地做到这一点,但如果你还想删除一些历史,请回显$HISTFILE来获取历史文件的位置(通常是~/.bash_history),取消设置HISTFILE,并编辑~/。bash_history(或者不管HISTFILE是什么-当然它现在是未设置的,所以你不能读取它)。

$ echo $HISTFILE       # E.g. ~/.bash_history
$ unset HISTFILE
$ vi ~/.bash_history   # Or your preferred editor

那你就编辑了你的历史,还有你编辑历史的事实!