我有一个crontab每小时运行一次。运行它的用户在.bash_profile中有环境变量,当用户从终端运行作业时,这些环境变量是有效的,然而,显然这些环境变量在crontab运行时不会被拾取。
我已经尝试在.profile和.bashrc中设置它们,但它们似乎仍然没有被拾取。有人知道我可以把crontab可以获取的环境变量放在哪里吗?
我有一个crontab每小时运行一次。运行它的用户在.bash_profile中有环境变量,当用户从终端运行作业时,这些环境变量是有效的,然而,显然这些环境变量在crontab运行时不会被拾取。
我已经尝试在.profile和.bashrc中设置它们,但它们似乎仍然没有被拾取。有人知道我可以把crontab可以获取的环境变量放在哪里吗?
当前回答
在@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源文件后面的任何命令都将拥有您的环境,就像您登录了一样。
其他回答
在@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源文件后面的任何命令都将拥有您的环境,就像您登录了一样。
在/etc/environment中设置变量在Ubuntu中也适用。从12.04开始,/etc/environment中的变量将为cron加载。
另一种方式-受此启发-“注入”变量如下(fcron的例子):
%daily 00 12 \
set -a; \
. /path/to/file/containing/vars; \
set +a; \
/path/to/script/using/vars
从帮助集:
-a标记已修改或创建用于导出的变量。 使用+而不是-会导致这些标志被关闭。
因此,set -和set +之间的所有内容都被导出到env中,然后可用于其他脚本,等等。如果不使用set,变量将只存在于set中。
除此之外,当程序需要一个非根帐户来运行,但你需要在其他用户的环境中使用一些变量时,传递变量也很有用。下面是一个传入nullmailer vars来格式化电子邮件头的例子:
su -s /bin/bash -c "set -a; \
. /path/to/nullmailer-vars; \
set +a; \
/usr/sbin/logcheck" logcheck
我在我的macbook上使用哦-我的-zsh,所以我已经尝试了很多方法来让crontab任务运行,但最后,我的解决方案是在运行命令之前前置.zshrc。
*/30 * * * * . $HOME/.zshrc; node /path/for/my_script.js
该任务每30分钟运行一次,并使用.zshrc配置文件执行我的节点命令。
别忘了在$HOME变量前加上点。
我尝试了大部分提供的解决方案,但一开始都没用。然而,事实证明,并不是解决方案失败了。显然,我的~/。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
我希望这对你有用