在 bash 历史记录中隐藏“history -d”

Kal*_*ing 14 command-line bash bash-history

如果我不小心在 bash 中输入了我的密码或任何其他敏感内容,我可以使用 轻松删除该行history -d ROW#,但我总是留下history -d ROW#历史记录中的命令,向所有人显示有人纠正了错误。

我可以在命令中附加一些内容以防止它出现在 bash 历史记录中吗?

des*_*ert 27

要不在历史记录中保存单个命令,只需在它前面加上一个空格(用?此处标记):

$ echo test
test
$ history | tail -n2
 3431  echo test
 3432  history | tail -n2
$ ?echo test2
test2
$ history | tail -n2
 3431  echo test
 3432  history | tail -n2
Run Code Online (Sandbox Code Playgroud)

此行为在您的~/.bashrc文件中设置,即在此行中:

HISTCONTROL=ignoreboth
Run Code Online (Sandbox Code Playgroud)

man bash 说:

HISTCONTROL
以冒号分隔的值列表,用于控制命令在历史列表中的保存方式。如果值列表包含 ignorespace则以空格字符开头的行不会保存在历史列表中ignoreups的值 会导致匹配前一个历史条目的行不被保存。ignoreboth的值 是ignorespaceignoreups 的简写。

ignoredups顺便说一下,这就是为什么history | tail -n2在上述测试中的历史记录中只出现一次的原因。


终端的历史记录保存在 RAM 中,并~/.bash_history在您关闭终端后立即刷新。如果你想删除你的特定条目,~/.bash_history你可以这样做sed

                                   # print every line…
sed '/^exit$/!d' .bash_history     # … which is just “exit”
sed '/^history/!d' .bash_history   # … beginning with “history”
sed '/>>log$/!d' .bash_history     # … ending with “>>log”
sed '\_/path/_!d' .bash_history    # … containing “/path/” anywhere
Run Code Online (Sandbox Code Playgroud)

在最后一个中,我将默认分隔符/更改_为在搜索词中使用,实际上这等于sed -i '/\/path\//d' .bash_history. 如果该命令仅输出要删除添加的线路-i选择和改变!d,以d执行删除操作:

                                   # delete every line…
sed -i '/^exit$/d' .bash_history   # … which is just “exit”
sed -i '/^history/d' .bash_history # … beginning with “history”
sed -i '/>>log$/d' .bash_history   # … ending with “>>log”
sed -i '\_/path/_d' .bash_history  # … containing “/path/” anywhere
Run Code Online (Sandbox Code Playgroud)


ste*_*ver 12

一种方法是设置HISTIGNORE环境变量。从man bash

HISTIGNORE
      A colon-separated list of patterns used to decide which  command
      lines  should  be  saved  on  the history list.  Each pattern is
      anchored at the beginning of the line and must  match  the  com?
      plete  line  (no  implicit  `*'  is  appended).  Each pattern is
      tested against the line after the checks specified  by  HISTCON?
      TROL  are  applied. 
Run Code Online (Sandbox Code Playgroud)

[FWIW,它是默认HISTCONTROL提供 type-a-space-in-front 解决方法]。

所以,例如

HISTIGNORE='history -d*'
Run Code Online (Sandbox Code Playgroud)

如果您希望它是持久的,请从您的 ~/.bashrc

export HISTIGNORE='history -d*'
Run Code Online (Sandbox Code Playgroud)


sud*_*dus 6

你可以

  • 关闭终端窗口。这会将您最近关闭(在其他窗口关闭后)的终端窗口中的最新历史记录刷新到文件中/home/$USER/.bash_history

  • /home/$USER/.bash_history不涉及情况下编辑文件bash,例如通过Alt+启动您喜欢的编辑器F2

    通过这种方式,您可以检查整个历史记录并删除您不再想要的任何命令。

    在此处输入图片说明

    在此处输入图片说明