我使用 Ubuntu 16.04 并尝试直接在 Bash 上执行:
sudo cat << EOF | at 'now + 1 minute'
echo "hello"
EOF
Run Code Online (Sandbox Code Playgroud)
我得到:
warning: commands will be executed using /bin/sh job 6
at Wed Dec 28 03:01:00 2016
Can't signal atd (permission denied)
Run Code Online (Sandbox Code Playgroud)
因此,鉴于没有运行该命令的权限,该短语hello
将不会在 Bash 上回显。
如果我使用sudo
,为什么会拒绝许可?与cd
which 不是实用程序而是内置 shell 命令不同,at
(以及cat
)是实用程序,因此sudo
应该应用它们。
你可能知道为什么 at 不能使用?
TL;DR:sudo
通过管道 ( |
)移动到at
命令本身。
at
以 root 身份运行。您cat
以 root ( sudo cat ...
)身份运行,并将输出通过管道传输cat
到at
,但您没有at
以 root 身份运行命令本身。
在许多系统上,允许一些非 root 用户在作业中运行。但是,如果这不是您想要的,您的系统已按照您喜欢的方式配置,并且您打算以 root 身份在作业中运行此特定作业,那么您可以通过at
以 root 身份而不是cat
. (无论哪种方式,cat
在这种情况下您都不需要以root身份运行。)
要做到这一点,把sudo
之前at
而不是cat
:
cat << EOF | sudo at 'now + 1 minute'
Run Code Online (Sandbox Code Playgroud)
目前你有:
sudo cat << EOF | at 'now + 1 minute'
echo "hello"
EOF
Run Code Online (Sandbox Code Playgroud)
That runs cat
as root with sudo
, passing echo "hello"
to it (with here-document syntax). The cat
command's standard output is piped to the command at 'now + 1 minute'
, which is not run as root. Therefore at
attempts to schedule the job as the non-root user who ran it (you).
If you want the at job to run as root, you can fix this problem by changing it to:
cat << EOF | sudo at 'now + 1 minute'
echo "hello"
EOF
Run Code Online (Sandbox Code Playgroud)
If you later configure a non-root user account that you're using to be permitted to run at jobs, then you would run neither command as root:
cat << EOF | at 'now + 1 minute'
echo "hello"
EOF
Run Code Online (Sandbox Code Playgroud)