I'm trying to write a simple bash function that sleeps X-number of mins and then runs a system sleep command (for me it's sudo pm-suspend since I'm on Ubuntu) right now the function looks like this:

function sleepin {
  sleep $(bc <<< $1*60); sudo pm-suspend

The first argument is after how many mins the sleep is supposed to happen. The problem is that after the sleep the script prompts me for the sudo password.

How should I re-write the script so that it doesn't prompt me for the sudo password after the sleep?

(I've tried to call sudo sleepin 30 but it still prompts me for the password. Note that if the sleep call is small enough bash doesn't prompts for password, but for a longer sleep it will..)

  • 2
    Why don't you simply authorize that command without a password in sudo's config?
    – Mat
    Aug 23 '13 at 8:57
  • 2
    If you do go down the NOPASSWD route, you may want to use sleep $(bc <<< $1*60) && sudo pm-suspend instead, so that if you Ctrl-C the function it wont run pm-suspend (and you can cancel it from suspending your OS).
    – Drav Sloan
    Aug 23 '13 at 10:04
  • Have you looked into modifying the timestamp_timeout default value in sudoers? You should be able to alter the timeout on a per-user basis.
    – Bratchley
    Aug 23 '13 at 12:52

Put the sleep inside the sudo command.

seconds=$(($1 * 60))
sudo sh -c "sleep $seconds; pm-suspend"

As Mat suggested, you can allow the user to run pm-suspend without a password.

Run sudo visudo

Add youruser ALL=(root) NOPASSWD: /path/to/pm-suspend


Going on a tangent: is there any particular reason you don't want to use the at daemon?

echo 'pm-suspend' | sudo at now + 15 minutes

might be a starting point.

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.