bash - 将 Zsh 历史保存到 ~/.persistent_history

标签 bash shell zsh

最近想在 Mac 上试试 Z shell。但我还想继续将命令历史记录保存到 ~/.persistent_history,这是我在 Bash 中所做的 (ref)。

但是,ref 链接中的脚本在 Zsh 下不起作用:

log_bash_persistent_history()
{
   [[
     $(history 1) =~ ^\ *[0-9]+\ +([^\ ]+\ [^\ ]+)\ +(.*)$
   ]]
   local date_part="${BASH_REMATCH[1]}"
   local command_part="${BASH_REMATCH[2]}"
   if [ "$command_part" != "$PERSISTENT_HISTORY_LAST" ]
   then
     echo $date_part "|" "$command_part" >> ~/.persistent_history
     export PERSISTENT_HISTORY_LAST="$command_part"
   fi
}
run_on_prompt_command()
{
   log_bash_persistent_history
}
PROMPT_COMMAND="run_on_prompt_command"

有没有人可以帮助我让它工作?非常感谢!

最佳答案

经过这么多谷歌搜索,我终于找到了这样做的方法。 首先,在 ~/.zshrc 中,添加以下历史操作选项:

setopt append_history # append rather then overwrite
setopt extended_history # save timestamp
setopt inc_append_history # add history immediately after typing a command

简而言之,这三个选项会立即将每个input_time+command记录到~/.zsh_history。 然后,把这个函数放到 ~/.zshrc 中:

precmd() { # This is a function that will be executed before every prompt
    local date_part="$(tail -1 ~/.zsh_history | cut -c 3-12)"
    local fmt_date="$(date -d @${date_part} +'%Y-%m-%d %H:%M:%S')"
    # For older version of command "date", comment the last line and uncomment the next line
    #local fmt_date="$(date -j -f '%s' ${date_part} +'%Y-%m-%d %H:%M:%S')"
    local command_part="$(tail -1 ~/.zsh_history | cut -c 16-)"
    if [ "$command_part" != "$PERSISTENT_HISTORY_LAST" ]
    then
        echo "${fmt_date} | ${command_part}"  >> ~/.persistent_history
        export PERSISTENT_HISTORY_LAST="$command_part"
    fi
}

因为我同时使用 bash 和 zsh,所以我想要一个可以保存它们所有历史命令的文件。在这种情况下,我可以使用“grep”轻松搜索所有这些。

关于bash - 将 Zsh 历史保存到 ~/.persistent_history,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30249853/

相关文章:

Linux 控制台上的 Python IDE

zsh - 为什么此代码在传递给 `zsh -n` 而不是传递给 `zsh` 时抛出错误?

bash - 有没有办法在 zsh 中获取任意 bash 脚本(即 msys2-packages "shell")?

bash - 我想连接两个 figlet 输出(不同颜色)

regex - Bash:用 curl 结果替换数组值

linux - 从日志文件中提取日志时间

macos - 我的 ZSH 完成在开始时不起作用,但当我获取 .zshrc (Mac) 时它们会起作用

bash- 获取两个文件中具有相同列值的所有行

linux - "less"命令如何获取标准输入?

windows - 获取 shell 图标的最快方法