如何在 shell 提示符中间歇性地显示我的历史命令编号?

发布于 2024-10-09 23:31:16 字数 805 浏览 0 评论 0原文

如何在 shell 提示符中间歇性地显示我的历史命令编号?例如,不要在每个提示中显示它,而是每 7 次显示一次。 (我使用的是 zsh,但我认为 bash 应该是几乎相同的。)我遇到的问题是 %h 在位于 PROMPT 变量中之前不会被计算,并且 $HISTCMD 由于某种原因总是被计算为 0。因此,将这样的函数放入我的提示符中会失败,因为 $HISTCMD 始终为 0:

prompt_history() {
CYCLE=$(( $HISTCMD % 7 ))
if [[ "$CYCLE" = "0" ]]; then
echo -ne "$HISTCMD"
fi
}

PROMPT="$(prompt_history) blah-blah >:"

这可以通过回显“%h”而不是“$HISTCMD”来部分修复,但只是部分修复。

更复杂的是,history 命令(似乎)不能在 .zshrc 文件中运行,因此类似这样的命令不起作用:(

CYCLE="$(( $(history 1 | wc -l) % 7 ))"

如果您使用的是 bash,请将“history 1”更改为“history “。)

此外,历史文件不能用作此信息的来源,因为(至少是我配置的方式——而且我不想更改此配置)历史记录在 zsh 会话关闭之前不会在会话之间共享它的历史记录被添加到我的 $HISTFILE 中。因此,这是行不通的:

CYCLE="$(( $(cat $HISTFILE | wc -l) % 7 ))"

我即将相信这目前是不可能的。我希望有人能证明我错了。

How can I intermittently show my history command number in my shell prompt? For instance, rather than showing it in EVERY prompt, just do it every 7 times. (I'm using zsh, but I think bash should be virtually identical.) The problem I encounter is that %h is not evaluated until it's in the PROMPT variable, and $HISTCMD is always evaluated as 0 for some reason. So putting a function like this into my prompt fails because $HISTCMD is always 0:

prompt_history() {
CYCLE=$(( $HISTCMD % 7 ))
if [[ "$CYCLE" = "0" ]]; then
echo -ne "$HISTCMD"
fi
}

PROMPT="$(prompt_history) blah-blah >:"

This can be partly fixed by echoing "%h" instead of "$HISTCMD", but only partly.

It is further complicated by the fact that the history command does not (seem to) function within a .zshrc file, so something like this won't work:

CYCLE="$(( $(history 1 | wc -l) % 7 ))"

(If you're using bash, change "history 1" to just "history".)

Also, the history file is not usable as a source of this information since (at least the way I have things configured--and I'd rather not change this configuration) history is not shared between sessions until a zsh session closes and its history is added to my $HISTFILE. Therefore, this won't work:

CYCLE="$(( $(cat $HISTFILE | wc -l) % 7 ))"

I'm on the verge of believing this is currently impossible. I'd love someone to prove me wrong.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云裳 2024-10-16 23:31:16

您只需推迟对提示的评估,直到发出提示为止。只需将双引号更改为单引号即可:

PROMPT='$(prompt_history) blah-blah >:'

You simply need to delay evaluation of the prompt until it's issued. Just change the double quotes to single quotes:

PROMPT='$(prompt_history) blah-blah >:'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文