Constantly updated clock in zsh prompt?

2020-02-17 08:11发布

I know that I can exec a date command in my zsh prompt. However, it shows the old time; to see the current time, I have to hit <return> and get a new prompt with the current time.

Is there a way to configure the zsh prompt to constantly update itself every second?

3条回答
淡お忘
2楼-- · 2020-02-17 08:41

This would be .... unpleasant in a standard zsh prompt (or bash, or other shells).

I suggest you'd be better off using Gnu Screen.

Screen can have a status line which can show the time. Here's an example screenrc scroll down to "Red Hat Magazine A guide to GNU Screen" to see the sample (i'll reproduce that here) which will, when screen is run, show the current time in the lower right corner of the terminal:

~/.screenrc

hardstatus alwayslastline
hardstatus string '%{= kG}[ %{G}%H %{g}][%= %{=kw}%?%-Lw%?%{r}(%{W}%n*%f%t%?(%u)%?%{r})%{w}%?%+Lw%?%?%= %{g}][%{B}%Y-%m-%d %{W}%c %{g}]'

# Default screens
screen -t shell1        0
screen -t shell2        1

http://www.gnu.org/software/screen/

查看更多
看我几分像从前
3楼-- · 2020-02-17 08:48

Note: I wrote this answer for a similar question, but seeing how this question has more views I think reposting my answer here would be useful.

This is in fact possible without resorting to strange hacks. I've got this in my .zshrc

RPROMPT='[%D{%L:%M:%S %p}]'

TMOUT=1

TRAPALRM() {
    zle reset-prompt
}

The TRAPALRM function gets called every TMOUT seconds (in this case 1), and here it performs a prompt refresh, and does so until a command starts execution (and it doesn't interfere with anything you type on the prompt before hitting enter).

Source: http://www.zsh.org/mla/users/2007/msg00944.html (It's from 2007!)

查看更多
姐就是有狂的资本
4楼-- · 2020-02-17 08:51

Sounds like a pleasant request to me. If anything it makes more sense than showing the time when the prompt was displayed.

Fortunately Peter Stephenson posted a technique. Try something like this in .zshrc:

PROMPT="[%T] %n@%M %~ %# "

schedprompt() {
  emulate -L zsh
  zmodload -i zsh/sched

  # Remove existing event, so that multiple calls to
  # "schedprompt" work OK.  (You could put one in precmd to push
  # the timer 30 seconds into the future, for example.)
  integer i=${"${(@)zsh_scheduled_events#*:*:}"[(I)schedprompt]}
  (( i )) && sched -$i

  # Test that zle is running before calling the widget (recommended
  # to avoid error messages).
  # Otherwise it updates on entry to zle, so there's no loss.
  zle && zle reset-prompt

  # This ensures we're not too far off the start of the minute
  sched +30 schedprompt
}

schedprompt
查看更多
登录 后发表回答