crontab环境变量
环境变量和命令
cron 最终使用一个 shell 执行每个命令。可以通过环境变量修改或定制 shell 的行为。
在 crontab 中很容易设置 shell 环境变量,只需要在crontab -e中输入:
PATH=/usr/bin:/bin:/usr/local/bin
指定一个有序的目录列表作为 shell 搜索路径。
cron 预定义了五个环境变量:
- PATH 的默认值是 /usr/bin:/bin
- SHELL 预设置为 /bin/sh。
- LOGNAME 初始化为 crontab 所有者的用户名。
- HOME 设置为 crontab 所有者的主目录,比如 /home/joe。
- MAILTO 设置为 crontab 所有者的名称。
要想修改这些默认值或设置任何变量,只需在 crontab 中设置适当的环境变量。
sh和bash
crontab中默认使用的shell是/bin/sh,使用sh调用执行脚本,相当于打开了bash的POSIX标准模式 (等效于bash的 —posix 参数)。一般的,sh是bash的“子集”,有些命令bash中有而sh中没有。如果登录时使用的是/bin/bash,手动运行脚本时没有问题,而在crontab中出错,检查一下是否是因为shell的问题。
调用相关
在脚本的调用方面(interactive、login相关),bash与sh也是存在差异 以下是详细说明(假如被调用执行的脚本名字叫xxx.sh)
BASH
交互式的登录shell (bash –il xxx.sh)
/etc/profile
~/.bash_profile( -> ~/.bashrc -> /etc/bashrc)
~/.bash_login
~/.profile
非交互式的登录shell (bash –l xxx.sh)
/etc/profile
~/.bash_profile ( -> ~/.bashrc -> /etc/bashrc)
~/.bash_login
~/.profile
$BASH_ENV
交互式的非登录shell (bash –i xxx.sh)
~/.bashrc ( -> /etc/bashrc)
非交互式的非登录shell (bash xxx.sh)
$BASH_ENV
SH
交互式的登录shell
/etc/profile
~/.profile
非交互式的登录shell
/etc/profile
~/.profile
交互式的非登录shell
$ENV
非交互式的非登录shell
nothing
由此可以看出,最主要的区别在于相关配置文件的是否载入, 而这些配置的是否载入,也就导致了很多默认选项的差异。
crontab修改
如果要保持crontab和手动运行环境一致,在crontab -e中加入
SHELL=/bin/bash
BASH_ENV=~/.bashrc
同时,如果~/.bashrc中有下面一句,则需要注释掉:
# If not running interactively, don't do anything
[ -z "$PS1" ] && return