开发者

Running a delayed command with 'sudo'

I want run a Bash script as root, but delayed. How can I achieve this?

sudo &开发者_C百科quot;sleep 3600; command" , or
sudo (sleep 3600; command)

does not work.


You can use at:

sudo at next hour

And then you have to enter the command and close the file with Ctrl+D. Alternatively you can specify commands to be run in a file:

sudo at -f commands next hour


If you really must avoid using cron:

sudo sh -c "(sleep 3600; command)&"


The simplest answer is:

sudo bash -c 'sleep 3600; command' &

Because sleep is a shell command and not an executable, and the semicolon is a shell “operator” too, it is a shell script, and hence needs to run in a shell. bash -c tells sudo to run bash and pass it a script to execute as a string.

Of course this will “hang” until command has actually finished running, or be killed if you exit the surrounding shell. I haven’t found a simple way to use nohup to prevent that here, and at that point, you’re basically reimplementing the at command anyway. I have found the above solution useful in many simple cases though. ;)

For anything more complex… of course you can always make a real shell script file, with a shebang (#! …) at the start, and run that. But I assume the whole point is that you wanted to avoid this for something that simple.

You could theoretically pass a string as a file using Bash’s … <( … ) syntax, but sudo expects it to be a real file, and marked as executable too, so that won’t work.


Use:

sleep 3600; sudo <command>

Anyway, I would consider using cron in your case…

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜