如何在会话间保留我的 bash 历史记录?

如何在会话间保留我的 bash 历史记录?

我正在研究运行 Fedora 9 的 x86 目标。

每当我重新启动它时,我的历史记录都会返回到某种状态,并且我没有在重新启动之前的会话中执行的命令。

我必须进行哪些更改才能更新重启之前的历史记录?

答案1

哪个历史记录?bash-history?如果您丢失了 bash 历史记录并且您一次有多个会话,那是因为每个会话都在覆盖其他会话的历史记录。

您可能想告诉 bash 不要每次都覆盖历史记录,而是将其附加到历史记录中。您可以通过修改 .bashrc 来运行 来实现这一点shopt -s histappend

您还可以通过将 HISTSIZE 导出为一个较大的数字来增加历史文件的大小(以字节为单位,因此 100000 应该足够了)。

答案2

我遇到了同样的问题 - 但我的文件.bashrc已经有了shopt -s histappend并且正确HISTFILE,,HISTSIZEHISTFILESIZE

对我来说,问题是我的.bash_history文件归而不是我的用户名,因此我的用户在退出时永远无法保存到该文件。

答案3

查找环境变量 HISTFILE、HISTSIZE、HISTFILESIZE。

答案4

我在 .bashrc 中写了几行代码,它们的作用如下:将每个命令之后的每个会话保存到一个文件中。历史文件的数量将与您启动过的终端数量相同。在启动新终端时,从最近的历史文件开始,将之前会话的所有历史文件加载到历史缓冲区中,直到达到行数阈值。

HISTCONTROL=''
HISTFOLDER=~/.bash_histories
HISTFILEEXT=history      # only files in $HISTFOLDER with this extension will be read
shopt -s histappend   # append when closing session
mkdir -p $HISTFOLDER
HISTFILE=$HISTFOLDER/$(date +%Y-%m-%d_%H-%M-%S_%N).$HISTFILEEXT  # create unique file name for this session. Nanoseconds seems to be unique enough, try: for ((i=0; i<=10; i++)); do date +%Y-%m-%d_%H-%M-%S_%N; done
# if HISTFILE unset, history is not saved on exit -> not really necessary if we save after each command, but its a double net safety
HISTSIZE=-1       # maximum number of commands to hold inside bash history buffer
HISTFILESIZE=-1   # maximum number of lines in history file
# history -a $HISTFILE # bash saves the total history commands entered since startup or since the last save and saves that amount of commands to the file. This means reading a history file after typing commands will trip up bash, but this won't be a problem if the history file is only loaded in the beginning. This means that only new commands are saved not all the old loaded commands, thereby we can load as many history files into the buffer as we want and still only save newly thereafter typed commands
PROMPT_COMMAND="history -a $HISTFILE; $PROMPT_COMMAND"  # This command is executed after very typed command -> save history after each command instead after only closing the session

# Load old histories from last 5 files/sessions
HISTLINESTOLOAD=2000
# --reverse lists newest files at first
names=($(ls --reverse $HISTFOLDER/*.$HISTFILEEXT 2>/dev/null))
toload=()
linecount=0
# Check if is really file and count lines and only append to $toload if linecount under $HISTLINESTOLOAD
for fname in ${names[*]}; do
    if test -f $fname; then
        linecount=$((linecount+$(wc -l < $fname) ))
        if test $linecount -ge $HISTLINESTOLOAD; then
            break
        fi
        toload+=($fname)
    fi
done
# Beginning with the oldest load files in $toload into bash history buffer
for (( i=${#toload[*]}-1; i>=0; i-- )); do
    history -r ${toload[$i]}
done

相关内容