1

I want to put the uptime command information into the command prompt and have it updated every 750ms (regardless of whether I'm typing at the prompt or not).

I usually use bash but I've used zsh too, which brings me here. I have a feeling that bash will not be sufficient and appreciate any help.


My apologies for missing this piece.

The intended prompt would look:

10:07:09 up 54 min,  7 users,  load average: 0.23, 0.38, 0.44
~/Videos ($)

I like the idea of the privilege level identifier in parentheses after the working directory. Then having the uptime information updating regularly, but it doesn't have to be 750ms.

Again, big sorry for not giving more info to start.

Thank you, everyone, in advance

0
2

With zsh:

TRAPALRM() { psvar[1]=$(uptime); zle reset-prompt; }
RPS1='%1v'
TMOUT=1

You'd have the output of uptime in the right prompt updated every second. For 750ms, you can't use $TMOUT which takes integers only.

You could do instead:

zmodload zsh/zselect
RPS1='%1v'
TRAPALRM() {
  (zselect -t 75; kill -s ALRM $$ 2> /dev/null) &|
  psvar[1]=$(uptime)
  [[ -z $WIDGET ]] || zle reset-prompt
}
precmd_functions+=(TRAPALRM)

Another approach could be to have a loop sending the uptime every 750ms as a coproc, using zle -F to handle the output of that coproc:

zmodload zsh/system
zmodload zsh/zselect
UPTIME_TMOUT=
coproc {
  while true; do
    zselect -r 0 ${UPTIME_TMOUT:+-t} $UPTIME_TMOUT
    case $? in
      (0) IFS= read UPTIME_TMOUT || exit
          [[ -n $UPTIME_TMOUT ]] || continue;;
      (1) ;;
      (*) exit 1;;
    esac
    uptime
  done
}
sysopen -wu UPTIME_TO   -o cloexec /dev/fd/3 3>&p
sysopen -ru UPTIME_FROM -o cloexec /dev/fd/3 3<&p

handle_uptime_event() {
  if ! IFS= read -ru $UPTIME_FROM 'psvar[1]'; then
    zle -F $UPTIME_FROM
    exec {UPTIME_FROM}<&- {UPTIME_TO}>&-
    unset UPTIME_TO UPTIME_FROM
  fi
  zle reset-prompt
}

start_uptime_loop() {
  (($+UPTIME_TO)) && print -u $UPTIME_TO 75
}
stop_uptime_loop() {
  (($+UPTIME_TO)) && print -u $UPTIME_TO
}
zle -F $UPTIME_FROM handle_uptime_event
precmd_functions+=(start_uptime_loop)
preexec_functions+=(stop_uptime_loop)

RPS1=%1v

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.