不能发表评论,但(这超出了一个简单的更正),所以我会添加这个答案。
This correction到the accepted answer完全不是那么回事的时候,例如,最后一个命令了相当多的时间来执行 - 你会得到流浪数字和你的命令;
,像这样:
2017-07-22 19:02:42 | 3;micro ~/.zshrc && . ~/.zshrc
这可以通过在command_part
与稍长gawk
,这也避免了我们一个管道更换sed -re '1s/.{15}//'
固定:
local command_part="$(gawk "
NR == $line_num_last {
pivot = match(\$0, \";\");
print substr(\$0, pivot+1);
}
NR > $line_num_last {
print;
}" ~/.zsh_history)"
它也有问题时deali使用多行命令,其中一行以:
开头。这可以(大部分)通过用grep -anE '^: [0-9]{10}:[0-9]*?;' ~/.zsh_history
代替line_num_last
中的grep -ane '^:' ~/.zsh_history
来解决 - 我说主要是因为一个命令可能包含一个匹配该表达式的字符串。再说了,
% naughty "multiline
> command
> ::123;but a command I'm not
> "
这将导致~/.persistent_history
一个惨败纪录。
为了解决这个问题,我们需要反过来,检查以前的redord是否有结束\
(可能还有其他的条件,但我不是这样的历史格式熟悉却又),如果是这样尝试之前的比赛。
_get_line_num_last() {
local attempts=0
local line=0
while true; do
# Greps the last two lines that can be considered history records
local lines="$(grep -anE '^: [0-9]{10}:[0-9]*?;' ~/.zsh_history | \
tail -n $((2 + attempts)) | head -2)"
local previous_line="$(echo "$lines" | head -1)"
# Gets the line number of the line being tested
local line_attempt=$(echo "$lines" | tail -1 | cut -d':' -f1 | tr -d '\n')
# If the previous (possible) history records ends with `\`, then the
# _current_ one is part of a multiline command; try again.
# Probably. Unless it was in turn in the middle of a multi-line
# command. And that's why the last line should be saved.
if [[ $line_attempt -ne $HISTORY_LAST_LINE ]] && \
[[ $previous_line == *"\\" ]] && [[ $attempts -eq 0 ]];
then
((attempts+=1))
else
line=$line_attempt
break
fi
done
echo "$line"
}
precmd() {
local line_num_last="$(_get_line_num_last)"
local date_part="$(gawk "NR == $line_num_last {print;}" ~/.zsh_history | cut -c 3-12)"
local fmt_date="$(date -d @${date_part} +'%Y-%m-%d %H:%M:%S')"
# I use awk itself to split the _first_ line only at the first `;`
local command_part="$(gawk "
NR == $line_num_last {
pivot = match(\$0, \";\");
print substr(\$0, pivot+1);
}
NR > $line_num_last {
print;
}" ~/.zsh_history)"
if [ "$command_part" != "$PERSISTENT_HISTORY_LAST" ]
then
echo "${fmt_date} | ${command_part}" >> ~/.persistent_history
export PERSISTENT_HISTORY_LAST="$command_part"
export HISTORY_LAST_LINE=$((1 + $(wc -l < ~/.zsh_history)))
fi
}
[这](http://superuser.com/questions/735660/whats-the-zsh-equivalent-of-bashs-prompt-command)应与替换'PROMPT_COMMAND'帮助。替换[[''用法应该可以用'grep -o'或'cut'或类似的方法来实现,但是取决于zsh中'history'的确切输出。 –
@EtanReisner非常感谢!对于'PROMPT_COMMAND',链接应该是有帮助的。对于''[''部分,我刚刚用'history'命令发现,bash会在最后一行给出最新的一个(在这种情况下,它是'history')。但是在Zsh下,'history'命令不会返回最新的命令,它会在最后一行返回'history'之前使用的命令。有任何想法吗? :-) – astroboylrx
那么,我没有理由重新发明轮子。只需设置'HISTFILE'并将'HISTSIZE'和'SAVEHIST'设置为一个非常大的尺寸(我的尺寸是100,000),并且我没有理由让它们变大,因为我在iTerm2中记录了所有终端会话 - 这就是所有命令+输出,在提示中时间缩短到秒)。默认的历史记录格式具有关联的POSIX时间戳,由于您没有tzinfo,所以它比您的更准确。 – 4ae1e1