如何通过Cron Job运行Shell脚本 [英] How to run a Shell Script by Cron Job
问题描述
我有一个Shell脚本如下
I have a Shell script like below
echo "Hello World"
脚本位于 / root / scripts /
文件夹 test .h
The script is located in /root/scripts/
folder as test.sh
我还创建了一个cron作业,如下所示
I also created a cron job like below
0-59 * * * * ./scripts/test.sh
cron作业每分钟不打印 test.sh
中的内容。
Now the cron job is not printing the content in test.sh
every minute.
让我知道我是否错误的目录或我的代码中有任何其他问题。
Let me know whether I have given a wrong directory or I have any other problem in my code.
推荐答案
我会
- 是显式的wrt。您的目录从
/root/scripts/test.sh
。我不知道cron会将其视为目前目录 - 将stdout重新导向日志文件,例如
... test.sh> /tmp/cron.log
(你可能想在某些阶段使用2>& 1
)重定向stderr。 否则,你不会看到输出。它会邮寄给cronjob所有者 - 确保您已授予对bash脚本的执行权限(
chmod + x /root/scripts/test.sh
) - 明确哪个脚本可执行文件将执行您的shell脚本。这是一个好的习惯,在顶部有一个脚本调用。
#!/ bin / sh
或类似
- Be explicit wrt. your directory to execute from e.g.
/root/scripts/test.sh
. I don't know what cron would regard as the current directory - Redirect stdout to a log file e.g.
...test.sh > /tmp/cron.log
(you would likely want to redirect stderr at some stage too using2>&1
). Otherwise you're not going to see the output. It gets mailed to the cronjob owner - Make sure you've given execution permission to your bash script (
chmod +x /root/scripts/test.sh
) - Be explicit which script executable will execute your shell script. It's good practise to have a script invocation at the top e.g.
#!/bin/sh
or similar
是臭名昭着的棘手。 Cron作业运行在一个大规模裁剪的环境中。打印出您的脚本可用的环境(使用 env
)并与您的交互式shell中可用的环境进行比较/对比是有益的。
Getting stuff to run under cron is notoriously tricky. Cron jobs run with a massively cut-down environment. It's instructive to print out the environment available to your script (use env
) and compare/contrast with what you have available from your interactive shell.
这篇关于如何通过Cron Job运行Shell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!