On Linux how to make `sudo` not ask password when chaining `sudo` commands? I don't want to disable asking password for a new `sudo` command, nor extend the `sudo` timeout which would also apply when not chaining commands, and don't want to nest commands in `bash -c` for instance.

The following is an example of my issue:

```bash
sudo whoami && \
sleep 512 && \
sudo whoami
```
```
root
root
```

```bash
sudo whoami && \
sleep 1024 && \
sudo whoami
```
```
root
[sudo] password for benjamin:
```
2/2
Mar 26, 4:49pm

On Linux, sudo caches your password for a certain duration (usually 15 minutes by default) after you enter it. If you run another sudo command within that time window, it will not ask for the password again. However, commands like sleep (which run for a long time) will cause the cached credentials to expire before the next sudo command is executed.

Solution: Extend the Cached Credentials Duration

You can extend the duration of the cached credentials only for the current terminal session by running a dummy sudo command just before the long-running command. This will refresh the cache and prevent the password prompt during the sleep period.

Example:

bash
sudo true && \
    sleep 1024 && \
    sudo whoami
  • sudo true refreshes the cached credentials, extending the timeout.
  • The sleep command will now run within the extended timeout window, so the next sudo command will not prompt for a password.

Why This Works

  • sudo true runs a command that does nothing, but it updates the cached credentials.
  • The cache is now extended for the duration configured in /etc/sudoers (default is 15 minutes).
  • Since sleep runs quickly, the cache remains valid for the next sudo command.

Note

This approach only affects the current terminal session and does not require modifying system-wide sudo settings or disabling password prompts for all commands.

Would you like to know how to check or adjust the default timeout in /etc/sudoers?

Mar 26, 4:49pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Le Chat can make mistakes. Check answers. Learn more