本文介绍了如何通过 Cron 作业运行 Shell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的 Shell 脚本

I have a Shell script like below

 echo "Hello World"

脚本位于 /root/scripts/ 文件夹中 test.sh

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.

推荐答案

我愿意

  1. 明确说明.您要执行的目录,例如/root/scripts/test.sh.我不知道 cron 会将什么视为 当前 目录
  2. 将标准输出重定向到日志文件,例如...test.sh >/tmp/cron.log(您可能希望在某个阶段也使用 2>&1 重定向 stderr).否则您将看不到输出.它会邮寄给 cronjob 所有者
  3. 确保您已授予 bash 脚本的执行权限 (chmod +x/root/scripts/test.sh)
  4. 明确哪个脚本可执行文件将执行您的 shell 脚本.在顶部进行脚本调用是一种很好的做法,例如#!/bin/sh 或类似的
  1. 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
  2. Redirect stdout to a log file e.g. ...test.sh > /tmp/cron.log (you would likely want to redirect stderr at some stage too using 2>&1). Otherwise you're not going to see the output. It gets mailed to the cronjob owner
  3. Make sure you've given execution permission to your bash script (chmod +x /root/scripts/test.sh)
  4. 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 下运行是出了名的棘手.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 作业运行 Shell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 00:46