我有一个crontab每小时运行一次。运行它的用户在.bash_profile中有环境变量,当用户从终端运行作业时,这些环境变量是有效的,然而,显然这些环境变量在crontab运行时不会被拾取。
我已经尝试在.profile和.bashrc中设置它们,但它们似乎仍然没有被拾取。有人知道我可以把crontab可以获取的环境变量放在哪里吗?
我有一个crontab每小时运行一次。运行它的用户在.bash_profile中有环境变量,当用户从终端运行作业时,这些环境变量是有效的,然而,显然这些环境变量在crontab运行时不会被拾取。
我已经尝试在.profile和.bashrc中设置它们,但它们似乎仍然没有被拾取。有人知道我可以把crontab可以获取的环境变量放在哪里吗?
当前回答
在crontab中设置的任何内容都可以在cronjob中使用,可以直接使用,也可以使用脚本中的变量。
在cronjob的定义中使用它们
你可以配置crontab,让它设置can cronjob使用的变量:
$ crontab -l
myvar="hi man"
* * * * * echo "$myvar. date is $(date)" >> /tmp/hello
现在/tmp/hello文件显示如下内容:
$ cat /tmp/hello
hi man. date is Thu May 12 12:10:01 CEST 2016
hi man. date is Thu May 12 12:11:01 CEST 2016
在cronjob运行的脚本中使用它们
您可以配置crontab,以便它设置脚本可以使用的变量:
$ crontab -l
myvar="hi man"
* * * * * /bin/bash /tmp/myscript.sh
然后输入script /tmp/myscript.sh如下所示:
echo "Now is $(date). myvar=$myvar" >> /tmp/myoutput.res
它生成一个文件/tmp/myoutput。res展示:
$ cat /tmp/myoutput.res
Now is Thu May 12 12:07:01 CEST 2016. myvar=hi man
Now is Thu May 12 12:08:01 CEST 2016. myvar=hi man
...
其他回答
你也可以在命令前加上env注入环境变量,如下所示:
0 * * * * env VARIABLE=VALUE /usr/bin/mycommand
展开@Robert Brisita刚刚展开,如果你不想在脚本中设置配置文件的所有变量,你可以在脚本顶部选择要导出的变量
在crontab -e文件中:
SHELL=/bin/bash
*/1 * * * * /Path/to/script/script.sh
在script.sh
#!/bin/bash
export JAVA_HOME=/path/to/jdk
some-other-command
以上所有解决方案都很有效。
当环境变量中有任何特殊字符时,就会产生问题。
我找到了解决方案:
eval $ (printenv | awk - f = '{打印“出口”“\”“1美元 "\"""=""\""$ 2 "\"" }' >> / 等/配置文件)
在crontab中设置的任何内容都可以在cronjob中使用,可以直接使用,也可以使用脚本中的变量。
在cronjob的定义中使用它们
你可以配置crontab,让它设置can cronjob使用的变量:
$ crontab -l
myvar="hi man"
* * * * * echo "$myvar. date is $(date)" >> /tmp/hello
现在/tmp/hello文件显示如下内容:
$ cat /tmp/hello
hi man. date is Thu May 12 12:10:01 CEST 2016
hi man. date is Thu May 12 12:11:01 CEST 2016
在cronjob运行的脚本中使用它们
您可以配置crontab,以便它设置脚本可以使用的变量:
$ crontab -l
myvar="hi man"
* * * * * /bin/bash /tmp/myscript.sh
然后输入script /tmp/myscript.sh如下所示:
echo "Now is $(date). myvar=$myvar" >> /tmp/myoutput.res
它生成一个文件/tmp/myoutput。res展示:
$ cat /tmp/myoutput.res
Now is Thu May 12 12:07:01 CEST 2016. myvar=hi man
Now is Thu May 12 12:08:01 CEST 2016. myvar=hi man
...
我尝试了大部分提供的解决方案,但一开始都没用。然而,事实证明,并不是解决方案失败了。显然,我的~/。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
我希望这对你有用