单独运行shell脚本与crontab运行shell脚本的区别

  crontab运行脚本存在两大问题:环境变量和路径,从而导致单独运行脚本没问题,但用crontab运行就报错。

1、环境变量

  描述问题:crontab: usage error: no arguments permitted after this option

  因为crontab不提供环境,所以需要自己在shell中加入,或者全部用绝对路径。简单的方法:控制台输入

[user@a ~]# echo $PATH
/your/path/1:/your/path/2………………

  然后在脚本中export

export PATH=/your/path/1:/your/path/2…………

2、路径

  描述问题:单独运行时能够找到文件,但crontab运行时找不到(诸如此类的问题)。

  如果你在脚本中用到了${PWD}等涉及相对路径的参数,就会出现这种问题。比如你的脚本放在/home/user/shell路径下,脚本中写的日志输出路径为${PWD}/shell.log,单独运行脚本时你可以在/home/user/shell下找到shell.log,但用crontab运行时,shell.log就会出现在/home/user目录下。可见,crontab运行shell时${PWD}中存储的是不是脚本所在路径,而是脚本执行用户的home路径。解决方法:使用绝对路径/home/user/shell/shell.log或修改为${PWD}/shell/shell.log。

原文地址:https://www.cnblogs.com/rouge/p/3698666.html