一半的 bash 历史记录丢失

一半的 bash 历史记录丢失

有一天晚上,我在阅读 AU 问答时使用了一个 bash 命令:

inxi -????

问题是,今天我不记得组成 ???? 的字符了。我想将命令和参数放入我的文档电子表格中。基于这个答案 (如何在终端中回忆历史记录)我使用了这个命令:

$ cat .bash_history | grep inxi
inxi -b
sudo apt install inxi
inxi -b

然而我想要的命令却不存在,尽管历史记录可以追溯到很久以前。inxi自那以后,我在终端中多次使用这些命令,但没有一个出现。

我也尝试过Ctrl++ Rinxi但没有任何效果。由于我经常打开多个终端窗口,所以历史记录是否与特定窗口绑定?

有没有不同的方法来grep打击历史文件?

请注意,我没有在终端命令前加上前缀,这样Space Bar它们就会被从历史记录中删除。

答案1

如果无法访问您的机器,我无法知道发生了什么,但这里是对历史系统如何工作的简短解释,这可能会帮助您弄清楚发生了什么。

每个打开的终端都有自己的历史缓冲区。$HISTFILE当终端关闭时,这些缓冲区会被附加到您的历史缓冲区中(也许当缓冲区已满时也会如此,但我不知道这种情况发生的频率)。现在,在您的历史记录中搜索命令的方法是简单地运行:

history | grep command

但如果该命令是在不同的 shell 中运行的,则您将无法在当前 shell 的历史记录中看到它。要解决此问题,请关闭所有打开的 shell,打开一个新的终端窗口,然后再次搜索历史记录。

如果这仍然没有帮助,那么你可能已经超过了存储在 中的命令的阈值$HISTFILE。 的行为$HISTFILE由各种环境变量控制(请参阅man bash了解完整列表),但以下相关的变量是:

   HISTSIZE
          The  number  of commands to remember in the command history (see HISTORY below).  If the value is 0, commands are not saved in the history list.  Numeric values less than
          zero result in every command being saved on the history list (there is no limit).  The shell sets the default value to 500 after reading any startup files.

   HISTFILESIZE
          The maximum number of lines contained in the history file.  When this variable is assigned a value, the history file is truncated, if necessary, to contain no  more  than
          that number of lines by removing the oldest entries.  The history file is also truncated to this size after writing it when a shell exits.  If the value is 0, the history
          file is truncated to zero size.  Non-numeric values and numeric values less than zero inhibit truncation.  The shell sets the default value to the value of HISTSIZE after
          reading any startup files.

你设置的值越高,你保存的命令就越多$HISTFILE。例如,我使用:

HISTSIZE=999999
HISTFILESIZE=999999

如果要将历史记录从一个shell导入到另一个shell,可以使用以下history命令:

$ help history | grep -E -- '-a|-r'
      -a    append history lines from this session to the history file
      -r    read the history file and append the contents to the history

因此,运行history -a以从一个终端写入历史记录,然后history -w从另一个终端读取它。现在,运行history将显示两个 shell 的历史记录。

最后,您可以通过将以下行添加到您的~/.bashrc

## history -a causes the last command to be written to the
## history file automatically and history -r imports the history
export PROMPT_COMMAND='history -a;history -r'

我还建议您添加以下内容:

## Make Bash append rather than overwrite the history on disk:
shopt -s histappend

答案2

你的命令对我有用......

$ cat .bash_history | grep inxi
inxi -b
sudo apt install inxi
inxi -b
inxi -Fxz -c 0 > inxi_list.txt
inxi -Fxz
inxi -Fxz
sudo inxi -Fxz

我还定期将历史记录复制到文件并保存。

history > history_$(date '+%Y-%m-%d_%H:%M:%S')_$(hostname).txt

相关内容