最近想在 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/