See whether sudo mode is on (password is cached) on the command-line prompt

by Byte Commander   Last Updated April 06, 2017 21:02 PM

I want to know whether it is possible to indicate on the command-line (ideally in the prompt), whether sudo mode is on.

By sudo mode I mean that I have already entered my password correctly once in this shell session and it has not expired yet but is still cached.

In other words, can I tell somehow whether the sudo command I'm going to run will ask me for my password or will use the cached credentials?



Answers 2


There is no command to directly show the remaining time for cached credentials, you would have to script it.

From https://unix.stackexchange.com/questions/115506/sudo-testing-for-credentials

sudo -nv 2> /dev/null

will give an exit value of 0 if the password is cached, you may be able to modify the script in that link or write your own.

Alternately the time stamps are stored in /var/lib/sudo so you could probably write a script to display or check the time stamp as well.

Panther
Panther
October 18, 2016 18:22 PM

For a long time, I have been using

sudo -S true < /dev/null 2> /dev/null

You might try that, but a recent update seems to have broken that since I now get a segmentation fault.

You might try sudo -n true 2> /dev/null (no -v). That seems to be working for me without renewing the timeout.

You can execute this in your prompt in various ways including something like:

PS1='\u:\w$(sudo -n true 2> /dev/null && echo " : sudo :") \$ '

This depends on the promptvars option which is enabled by default.

Note that once the prompt is issued, the indicator isn't updated again. So if the prompt sits there until the timeout expires, it may indicate that sudo is active even though it's expired.

Dennis Williamson
Dennis Williamson
April 06, 2017 20:54 PM

Related Questions



A noob question about sudo -s

Updated April 02, 2017 16:02 PM