How can I intermittently show my history command n

2019-06-28 04:49发布

问题:

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.

回答1:

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 >:'


标签: linux shell zsh