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

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


当前回答

而不是

0  *  *  *  *  sh /my/script.sh

使用bash -l -c

0  *  *  *  *  bash -l -c 'sh /my/script.sh'

其他回答

对我有用的(基于debian):

创建一个包含所有需要的env变量的文件: # !/bin/bash env | grep VAR1= > /etc/environment . env | grep VAR1= > /etc/environment . env | /etc/environment . env | grep VAR2= >> /etc/environment . env | grep VAR3= >> 然后,通过在调用需要它的脚本之前调用env文件来构建crontab内容,从而启动cron服务 (crontab -l;Echo '* * * * *。/etc/environment;/usr/local/bin/python /mycode.py >> /var/log/cron-1.log 2>&1') | crontab 服务cron启动

注意:对于python用例,一定要调用整个python路径,否则可能会调用错误的python,产生无意义的语法错误

对于我来说,我必须为php应用程序设置环境变量。我通过向crontab添加以下代码来解决这个问题。

$ sudo  crontab -e

定时任务:

ENVIRONMENT_VAR=production

* * * * * /home/deploy/my_app/cron/cron.doSomethingWonderful.php

在doSomethingWonderful.php我可以得到的环境值:

<?php     
echo $_SERVER['ENVIRONMENT_VAR']; # => "production"

我希望这能有所帮助!

在/etc/environment中设置变量在Ubuntu中也适用。从12.04开始,/etc/environment中的变量将为cron加载。

我尝试了大部分提供的解决方案,但一开始都没用。然而,事实证明,并不是解决方案失败了。显然,我的~/。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

我希望这对你有用

以上所有解决方案都很有效。

当环境变量中有任何特殊字符时,就会产生问题。

我找到了解决方案:

eval $ (printenv | awk - f = '{打印“出口”“\”“1美元 "\"""=""\""$ 2 "\"" }' >> / 等/配置文件)