我有一个crontab每小时运行一次。运行它的用户在.bash_profile中有环境变量,当用户从终端运行作业时,这些环境变量是有效的,然而,显然这些环境变量在crontab运行时不会被拾取。

我已经尝试在.profile和.bashrc中设置它们,但它们似乎仍然没有被拾取。有人知道我可以把crontab可以获取的环境变量放在哪里吗?


当前回答

不幸的是,crontab的环境变量范围非常有限,因此每次运行corntab时都需要导出它们。

一个简单的方法是下面的例子,假设你的env变量在一个名为env的文件中,然后:

* * * * * ../env && /path/to_your/command

此部分. ./env将导出它们,然后在您的命令的相同范围内使用它们

其他回答

我尝试了大部分提供的解决方案,但一开始都没用。然而,事实证明,并不是解决方案失败了。显然,我的~/。Bashrc文件以以下代码块开始:

case $- in
    *i*) ;;
    *) return;;
esac

This basically is a case statement that checks the current set of options in the current shell to determine that the shell is running interactively. If the shell happens to be running interactively, then it moves on to sourcing the ~/.bashrc file. However, in a shell invoked by cron, the $- variable doesn't contain the i value which indicates interactivity. Therefore, the ~/.bashrc file never gets sourced fully. As a result, the environment variables never got set. If this happens to be your issue, feel free to comment out the block of code as follows and try again:

# case $- in
#     *i*) ;;
#     *) return;;
# esac

我希望这对你有用

从命令行运行crontab -e时,可以在crontab本身中定义环境变量。

LANG=nb_NO.UTF-8
LC_ALL=nb_NO.UTF-8
# m h  dom mon dow   command

* * * * * sleep 5s && echo "yo"

此特性仅适用于特定的cron实现。Ubuntu和Debian目前使用vixie-cron,它允许在crontab文件中声明这些(也可以是GNU mcron)。

Archlinux和RedHat使用cronie,它不允许声明环境变量,并且会在cron.log中抛出语法错误。每个条目都可以采取变通措施:

# m h  dom mon dow   command
* * * * * export LC_ALL=nb_NO.UTF-8; sleep 5s && echo "yo"

在@carestad示例的基础上展开(我觉得更简单),使用cron运行脚本,并将环境放在脚本中。

在crontab -e文件中:

SHELL=/bin/bash

*/1 * * * * $HOME/cron_job.sh

cron_job.sh文件:

#!/bin/bash
source $HOME/.bash_profile
some_other_cmd

.bash_profile源文件后面的任何命令都将拥有您的环境,就像您登录了一样。

如果你通过cron开始执行脚本:

#!/bin/bash -l

他们应该捡起你的~/。Bash_profile环境变量

对我来说,我必须在NodeJS文件中指定路径。

// did not work!!!!!
require('dotenv').config()

而不是

// DID WORK!!
require('dotenv').config({ path: '/full/custom/path/to/your/.env' })