40

This is hackish.

I sometimes need to quickly run programs one after the other in the terminal with some commands needing sudo while others do not, such as:

$ command1; c2; sudo c3 | c4; c5 | sudo c6; c7; sudo c8

I would like to initiate sudo (aka type the password) before command1 so that there will be no bottleneck in c3 waiting for the password.

Most of the time, I initiate sudo using a random command I haphazardly typed in the keyboard, like:

$ sudo laksdfjlskjf; command1; c2; sudo c3 | c4; c5 | sudo c6; c7; sudo c8

It says command not found for laksdfjlskjf, but I've successfully done what I need to do: initiate sudo. No bottleneck in c3.

Question:

Is there a better way than typing (non-)random characters to initiate sudo? Is there a safe command that does nothing and so is safe to use sudo on?

Majal
  • 1,048

3 Answers3

62

sudo -v is exactly for this. From man 8 sudo:

-v, --validate
Update the user's cached credentials, authenticating the user if necessary. For the sudoers plugin, this extends the sudo timeout for another 5 minutes by default, but does not run a command. Not all security policies support cached credentials.

The complementary command is sudo -k, it invalidates the user's cached credentials.

While I think sudo -v is the Right Thing, I admit one has to remember the option to use it without consulting the manual. This is a downside. As an alternative almost any harmless command can be used with sudo to achieve your goal; so if you happen not to remember -v at the moment, use sudo true, sudo echo or sudo date (credits go to the linked answers).


sudo -v should work for you in cases where your original approach works. In your example, if command1 and c2 take more time than it takes for sudo to forget the cached credentials then sudo c3 will ask for your password. And so on. sudo -v can replace your sudo laksdfjlskjf, but in case of long-running command(s) preceding sudo neither will work.

If the line you want to run contains long-running command(s) (not excluding sudo commands) before some sudo then consider repeating sudo -v in the background frequently enough. Example:

sudo -v    # in the foreground, so you can input your password if needed
while sudo -v; do sleep 58; done &
command1; c2; sudo c3 | c4; c5 | sudo c6; c7; sudo c8; kill "$!"
23

How about true? Description: The true utility always returns with an exit code of zero.

If you want something shorter, try id. It returns user identity (and doesn't change the system in any way).

7

What about a simple echo or echo -n to suppress the line break?