【问题标题】:Impossible to run .sh Script with crontab无法使用 crontab 运行 .sh 脚本
【发布时间】:2021-06-27 10:57:13
【问题描述】:

我正在尝试将我的 script.sh 脚本安排为从周一到周五每天上午 9:35 运行。当我直接在终端中使用 ./ 运行我的脚本时,一切正常。但是当我尝试在 crontab -e 中运行时,没有任何效果。 这是我尝试过的列表:

- * * * * * root /bin/script.sh
- * * * * * root sh /bin/script.sh
- * * * * * root bash /bin/script.sh
- * * * * * root / bin / sh /bin/script.sh
- * * * * * /bin/script.sh
- * * * * * sh /bin/script.sh
- * * * * * bash /bin/script.sh
- * * * * * / bin / sh /bin/script.sh

我每分钟执行一次,只是为了测试。 否则最终的命令会是这样的:

- 35 9 * * 1-5 /bin/script.sh

我一定忘记了一个重要的步骤或什么的。 当然,我每次修改都会重新启动cron:

- service cron restart

【问题讨论】:

    标签: linux bash shell cron


    【解决方案1】:

    应该可以的

    * * * * * /bin/bash /bin/script.sh
    

    您还可以在脚本的开头添加一个 shebang

    #!/bin/bash
    
    ... your script here ...
    

    这将允许您通过使用 /bin/script.sh 调用它来直接执行脚本 系统会知道他需要启动 bash 来执行 您需要获得执行权限

    chmod +x /bin/script.sh
    

    这将授予任何人执行权限,如果您想只授予所有者执行权限,请检查 chmod man

    cron 就是这样

    * * * * * /bin/script.sh
    

    请记住,您不会通过 cron 获得任何输出,您仍然可以将 stdout 重定向到日志文件

    * * * * * /bin/script.sh >> /var/log/myscript.log
    

    如果你使用 crontab -e 作为 root,你不需要使用 sudo 或类似的东西

    【讨论】:

    • 感谢您的回答!我也已经这样做了:)
    • @LyesBenchoubane 你做到了吗?它仍然无法正常工作?还是成功了?
    • 我尝试添加日志文件。我马上告诉你!谢谢
    • 所以我尝试添加 * * * * * /bin/script.sh >> /var/log/myscript.log,重启等待3分钟。但是没有输出。我需要创建 myscript.log 吗? (我不认为)
    • 不,它应该自己创建。检查 /var/log/syslog 中是否有任何错误您可以执行 grep CRON /var/log/syslog 以获取所有与 cron 相关的错误
    最近更新 更多