Update Zsh prompt with sudo timeout information

promptsudozsh

I would like my Zsh prompt to display whether my sudo credentials are cached.
What I have so far should help in explaining what I want to achieve.

function sudo-warning {
    if sudo -nl &>/dev/null; then
        echo -n " %{${fg[red]}%}?%{$reset_color%}"
    # optionally, show a locked lock if no sudo credentials active
    #else
    #    echo -n " %{${fg[blue]}%}?%{$reset_color%}"
    fi  
}

# Update prompt every 10 seconds
TMOUT=10
TRAPALRM() {
    zle reset-prompt
}

PROMPT='%n$(sudo-warning) '

The problem is that sudo -nl &>/dev/null updates the timestamp of the last sudo call, so no timeout is ever reached.
So, is there a way to get retrieve information about whether sudo still has my credentials cached, without updating the timeout itself?

Best Answer

This seems to work for me to tell whether the timeout is reached:

sudo-expired() [[ $(
  trap "" XFSZ
  limit filesize 0
  LC_ALL=C sudo -n true 2>&1) = *"password is required" ]]

That is, set the filesize limit to 0 for the update of the timestamp file to fail, but as long as we don't let that limit kill sudo, we're still able to tell if a password was required or not.

Used like in yours (with a few simplifications):

sudo-warning()
  if sudo-expired; then
    echo '%F{blue}?%f'
  else
    echo '%F{red}?%f'
  fi

TMOUT=10
TRAPALRM() zle reset-prompt
set -o promptsubst
PS1='%n$(sudo-warning) '
Related Question