Ubuntu – Run a command that requires sudo after a time has passed

bashscriptssudo

I usually do

sleep 4h; command

to execute a command after 4h. However, if that command requires sudo, it'll not work.

Is it possible to give sudo permission at the moment I'm running the sleep command?

Best Answer

Use sudo to start a root shell where you run the commands:

sudo bash -c 'sleep 4h; command'

Every command running in the root shell runs with root permissions, which for sleep doesn’t hurt. If you need to run a command with user permissions in it, use sudo -u USERNAME COMMAND, e.g.:

$ sudo bash -c 'sleep 4h; sudo -u dessert whoami; whoami'
dessert  # whoami run as user dessert
root     # whoami run as root

Another approach would be to use sudo visudo to allow the command’s execution without root access, see: How to allow execution without prompting for password using sudo?
Note that depending on the command this may create a security flaw.