使用 crontab 来定时执行脚本,无法执行,但是如果直接通过命令(如:./test.sh)又可以正常执行,

脚本无法执行问题

如果我们使用 crontab 来定时执行脚本,无法执行,但是如果直接通过命令(如:./test.sh)又可以正常执行,这主要是因为无法读取环境变量的原因。

解决方法:

  • 1、所有命令需要写成绝对路径形式,如: /usr/local/bin/docker。

  • 2、在 shell 脚本开头使用以下代码:

  • #!/bin/sh
    
    . /etc/profile
    . ~/.bash_profile
    

     3、在 /etc/crontab 中添加环境变量,在可执行命令之前添加命令 . /etc/profile;/bin/sh,使得环境变量生效,例如:

  • 20 03 * * * . /etc/profile;/bin/sh /var/www/runoob/test.sh
    

      转自:https://www.runoob.com/linux/linux-comm-crontab.html

原文地址:https://www.cnblogs.com/wang-yaz/p/14200809.html