从命令行 bash 运行时,无法从 crontab 运行 bash 脚本 [英] Cannot run bash script from crontab when it works from command line bash

查看:23
本文介绍了从命令行 bash 运行时,无法从 crontab 运行 bash 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的问题,即能够从命令行运行 bash 脚本,但不能从 root 的 crontab 条目运行.我正在运行 Ubuntu 12.04.

I have a strange problem of being to able to run a bash script from commandline but not from the crontab entry for root. I am running Ubuntu 12.04.

* * * * 1-5 root /home/xxxxxx/jmeter/VerificationService-0.0.1-SNAPSHOT/jmeter-cron-randomise.sh >> /home/xxxxxxx/jmeter/VerificationService-0.0.1-SNAPSHOT/cron.log

如果我使用 bash 从 cmd 行运行脚本,它可以正常工作但 sh 失败并出现以下错误:

If I run the script from the cmd line using bash, it works fine but sh fails with following error:

> jmeter-cron-randomise.sh: 7: jmeter-cron-randomise.sh: arithmetic
> expression: expecting primary: "  % 1 "

在 google 上搜索了这个问题,似乎标准 shell 没有与 bash 相同的数学运算符,如 %(模数).我不确定为什么脚本中的 cron 作业失败?我假设这是因为它没有使用 bash shell?它肯定是由 cron 守护进程触发的(可以在/var/log/syslog 中看到它).非常感谢任何帮助.

Having googled the problem, it seems like standard shell doesn't have the same math operators, like % (modulus), as bash. I'm Not sure why the cron job is failing in the script? I am assuming it is because it's not using the bash shell? It's definitely being fired by the cron daemon (can see it in /var/log/syslog). Any help much appreciated.

推荐答案

您可能需要告诉 cron 要使用的 shell 是 bash shell,因为它默认为 sh.您可以通过将此行放在您的 crontab 中来为所有 crontab 条目执行此操作:

You likely need to tell cron that the shell to use is the bash shell as it defaults to sh. You can do that for all crontab entries by putting this line in your crontab:

SHELL=/bin/bash

请注意,这将导致 crontab 中的所有脚本都在 bash 下运行,这可能不是您想要的.如果您想将 crontab 行本身更改为只运行 bash,请将其更改为:

Note that this will cause all scripts in the crontab to be run under bash which may not be what you want. If you want to change the crontab line itself to just run bash, change it to this:

* * * * 1-5 root /bin/bash /home/xxxxxx/jmeter/VerificationService-0.0.1-SNAPSHOT/jmeter-cron-randomise.sh >> /home/xxxxxxx/jmeter/VerificationService-0.0.1-SNAPSHOT/cron.log 2>&1

请注意,我还导致将 stderr 写入 cron.log 文件 (2>&1),这可能不是您想要的,但很常见.这可能有助于您进一步诊断脚本中的错误.

Note that I have also caused stderr to be written to the cron.log file (2>&1) which may not be what you want but is pretty common practice. This may help you further diagnose errors from the script.

这篇关于从命令行 bash 运行时,无法从 crontab 运行 bash 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆