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
    #    echo -n " %{${fg[blue]}%}🔒%{$reset_color%}"

# Update prompt every 10 seconds
    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?


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

  if sudo-expired; then
    echo '%F{blue}🔒%f'
    echo '%F{red}🔓%f'

TRAPALRM() zle reset-prompt
set -o promptsubst
PS1='%n$(sudo-warning) '
  • This is a very nice and clever hack! The nice thing about limiting the file size is that no emails are sent out, even if mail_badpass is set. This works perfectly for me. However, this might also be considered a security issue. I’ll try to contact the developers about this. – timothymctim Jan 3 '18 at 14:14
  • @timothymctim, note that I've already contacted the sudo (and some distro) maintainers a few years back about the implications of changing the limits (and other process attributes like signal handler). – Stéphane Chazelas Jan 3 '18 at 14:18

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.