crontab环境变量

2018-03-14 1614 0

环境变量和命令

cron 最终使用一个 shell 执行每个命令。可以通过环境变量修改或定制 shell 的行为。

在 crontab 中很容易设置 shell 环境变量,只需要在crontab -e中输入:

  1. PATH=/usr/bin:/bin:/usr/local/bin

指定一个有序的目录列表作为 shell 搜索路径。

cron 预定义了五个环境变量:

  1. PATH 的默认值是 /usr/bin:/bin
  2. SHELL 预设置为 /bin/sh。
  3. LOGNAME 初始化为 crontab 所有者的用户名。
  4. HOME 设置为 crontab 所有者的主目录,比如 /home/joe。
  5. 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

  1. 交互式的登录shell (bash –il xxx.sh)

    1. /etc/profile
    2. ~/.bash_profile( -> ~/.bashrc -> /etc/bashrc
    3. ~/.bash_login
    4. ~/.profile
  2. 非交互式的登录shell (bash –l xxx.sh)

    1. /etc/profile
    2. ~/.bash_profile ( -> ~/.bashrc -> /etc/bashrc
    3. ~/.bash_login
    4. ~/.profile
    5. $BASH_ENV
  3. 交互式的非登录shell (bash –i xxx.sh)

    1. ~/.bashrc ( -> /etc/bashrc
  4. 非交互式的非登录shell (bash xxx.sh)

    1. $BASH_ENV

SH

  1. 交互式的登录shell

    1. /etc/profile
    2. ~/.profile
  2. 非交互式的登录shell

    1. /etc/profile
    2. ~/.profile
  3. 交互式的非登录shell

    1. $ENV
  4. 非交互式的非登录shell

    1. nothing

由此可以看出,最主要的区别在于相关配置文件的是否载入, 而这些配置的是否载入,也就导致了很多默认选项的差异。

crontab修改

如果要保持crontab和手动运行环境一致,在crontab -e中加入

  1. SHELL=/bin/bash
  2. BASH_ENV=~/.bashrc

同时,如果~/.bashrc中有下面一句,则需要注释掉:

  1. # If not running interactively, don't do anything
  2. [ -z "$PS1" ] && return