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?
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.
Assuming you only want to run the process once (not, e.g. every 4 hours) then you can use atd
/etc/init.d/atd status or better still systemctl status atd)At a terminal as root run your command as follows:
# at now + 4 hours
warning: commands will be executed using /bin/sh
at> command
at> CTRL-D
If you want to run it every 4 hours you could also use cron (as root) with the following config in your crontab
0 */4 * * * sh -c $'/path/to/command'
One way is to run via a shellscript with sudo permissions (and give the password, when you start the shellscript), if the shellscript is in the current directory,
sudo ./delayer 4h
where delayer can be a shellscript with the content
#!/bin/bash
sleep "$1"
command
Make it executable with
chmod +x delayer
and copy or move it to a directory in PATH if you wish.
If you want a more flexible shellscript, where you can select the command [line] to delay by entering parameter(s), you can try
#!/bin/bash
if [ $# -lt 2 ] || [ "$(whoami)" != "root" ]
then
echo "Delay start of command, that needs 'sudo'
Usage: sudo $0 <delay> <command line>
Example: sudo $0 4h parted -ls"
exit
fi
sleep "$1"
shift
"$@"
Demo example (short delay, 5s, for demo purpose),
$ ./delayer
Delay start of command, that needs 'sudo'
Usage: sudo ./delayer <delay> <command line>
Example: sudo ./delayer 4h parted -ls
$ sudo ./delayer 5s parted /dev/sdc p
[sudo] password for sudodus:
Model: Kanguru SS3 (scsi)
Disk /dev/sdc: 15,9GB
Sector size (logical/physical): 512B/512B
Partition Table: gpt
Disk Flags:
Number Start End Size File system Name Flags
2 1049kB 2097kB 1049kB primary bios_grub
3 2097kB 258MB 256MB fat32 primary boot, esp
4 258MB 2274MB 2016MB primary
5 2274MB 12,5GB 10,2GB ext2 primary
1 12,5GB 15,9GB 3394MB ntfs primary msftdata
Another way would be to start sudo interactive session with sudo -s (does not change directory) or sudo -i (changes current directory to root home directory) and then enter your commands (without sudo)