使用“sudo”运行延迟命令;
我想以 root 身份运行 Bash 脚本,但延迟了。我怎样才能实现这个目标?
sudo "sleep 3600; command" , or
sudo (sleep 3600; command)
不起作用。
I want run a Bash script as root, but delayed. How can I achieve this?
sudo "sleep 3600; command" , or
sudo (sleep 3600; command)
does not work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 at:
然后您必须输入命令并关闭文件Ctrl+D。或者,您可以指定要在文件中运行的命令:
You can use at:
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:
如果您确实必须避免使用 cron:
If you really must avoid using cron:
最简单的答案是:
因为
sleep
是一个 shell 命令,而不是一个可执行文件,而分号也是一个 shell“操作符”,它是一个 shell 脚本,因此需要在 shell 中运行。 bash -c 告诉 sudo 运行 bash 并向其传递一个脚本以作为字符串执行。当然,这将“挂起”,直到命令实际完成运行,或者如果退出周围的 shell,它就会被终止。我还没有找到一种简单的方法来使用 nohup 来防止这种情况发生,此时,您基本上是在重新实现 at 命令。我发现上述解决方案在许多简单的情况下很有用。 ;)
对于任何更复杂的事情...当然,您始终可以创建一个真正的 shell 脚本文件,并在开头使用 shebang (
#! ...
),然后运行它。但我认为重点是你想避免这种简单的事情。理论上,您可以使用 Bash 的
... <( ... )
语法将字符串作为文件传递,但sudo
期望它是一个真实的文件,并且也标记为可执行文件,因此那是行不通的。The simplest answer is:
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
tellssudo
to runbash
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 usenohup
to prevent that here, and at that point, you’re basically reimplementing theat
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, butsudo
expects it to be a real file, and marked as executable too, so that won’t work.使用:
无论如何,我会考虑在你的情况下使用 cron ...
Use:
Anyway, I would consider using cron in your case…