Linux 我在哪里可以设置 crontab 将使用的环境变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2229825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 19:45:56  来源:igfitidea点击:

Where can I set environment variables that crontab will use?

linuxunixenvironment-variablescrontab

提问by James

I have a crontab running every hour. The user running it has environment variabless in the .bash_profilethat work when the user runs the job from the terminal, however, obviously these don't get picked up by crontab when it runs.

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

I've tried setting them in .profileand .bashrcbut they still don't seem to get picked up. Does anyone know where I can put environment vars that crontab can pick up?

我试过将它们放入.profile.bashrc但它们似乎仍然没有被接住。有谁知道我可以在哪里放置 crontab 可以获取的环境变量?

采纳答案by Jonathan Leffler

Have 'cron' run a shell script that sets the environment before running the command.

让“cron”运行一个 shell 脚本,在运行命令之前设置环境。

Always.

总是。

#   @(#)$Id: crontab,v 4.2 2007/09/17 02:41:00 jleffler Exp $
#   Crontab file for Home Directory for Jonathan Leffler (JL)
#-----------------------------------------------------------------------------
#Min     Hour    Day     Month   Weekday Command
#-----------------------------------------------------------------------------
0        *       *       *       *       /usr/bin/ksh /work1/jleffler/bin/Cron/hourly
1        1       *       *       *       /usr/bin/ksh /work1/jleffler/bin/Cron/daily
23       1       *       *       1-5     /usr/bin/ksh /work1/jleffler/bin/Cron/weekday
2        3       *       *       0       /usr/bin/ksh /work1/jleffler/bin/Cron/weekly
21       3       1       *       *       /usr/bin/ksh /work1/jleffler/bin/Cron/monthly

The scripts in ~/bin/Cron are all links to a single script, 'runcron', which looks like:

~/bin/Cron 中的脚本都是指向单个脚本 'runcron' 的链接,它看起来像:

:       "$Id: runcron.sh,v 2.1 2001/02/27 00:53:22 jleffler Exp $"
#
#       Commands to be performed by Cron (no debugging options)

#       Set environment -- not done by cron (usually switches HOME)
. $HOME/.cronfile

base=`basename 
:       "@(#)$Id: weekday.sh,v 1.10 2007/09/17 02:42:03 jleffler Exp $"
#
#       Commands to be done each weekday

# Update ICSCOPE
n.updics
` cmd=${REAL_HOME:-/real/home}/bin/$base if [ ! -x $cmd ] then cmd=${HOME}/bin/$base fi exec $cmd ${@:+"$@"}

(Written using an older coding standard - nowadays, I'd use a shebang '#!' at the start.)

(使用较旧的编码标准编写 - 现在,我会在开头使用 shebang '#!'。)

The '~/.cronfile' is a variation on my profile for use by cron - rigorously non-interactive and no echoing for the sake of being noisy. You could arrange to execute the .profile and so on instead. (The REAL_HOME stuff is an artefact of my environment - you can pretend it is the same as $HOME.)

'~/.cronfile' 是我的个人资料的一个变体,供 cron 使用 - 严格地非交互性并且为了嘈杂而没有回声。您可以安排执行 .profile 等。(REAL_HOME 的东西是我的环境的人工制品 - 您可以假装它与 $HOME 相同。)

So, this code reads the appropriate environment and then executes the non-Cron version of the command from my home directory. So, for example, my 'weekday' command looks like:

因此,此代码读取适当的环境,然后从我的主目录执行该命令的非 Cron 版本。因此,例如,我的“工作日”命令如下所示:

:       "@(#)$Id: daily.sh,v 1.5 1997/06/02 22:04:21 johnl Exp $"
#
#       Commands to be done daily

# Nothing -- most things are done on weekdays only

exit 0

The 'daily' command is simpler:

“每日”命令更简单:

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

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

回答by carestad

You can define environment variables in the crontab itself when running crontab -efrom the command line.

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

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

This feature is only available to certain implementations of cron. Ubuntu and Debian currently use vixie-cronwhich allows these to be declared in the crontab file (also GNU mcron).

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

Archlinuxand RedHatuse croniewhich does notallow environment variables to be declared and will throw syntax errors in the cron.log. Workaround can be done per-entry:

ArchlinuxRedHat使用cronie不允许声明环境变量,并且会在 cron.log 中抛出语法错误。解决方法可以按条目完成:

0 5 * * * . $HOME/.profile; /path/to/command/to/run

回答by Vishal

I got one more solution for this problem:

我为这个问题找到了另一种解决方案:

SHELL=/bin/bash

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

In this case it will pick all the environment variable defined in your $HOME/.profilefile.

在这种情况下,它将选择$HOME/.profile文件中定义的所有环境变量。

Of course $HOMEis also not set, you have to replace it with the full path of your $HOME.

当然$HOME也没有设置,你必须用你的$HOME.

回答by Robert Brisita

Expanding on @carestad example, which I find easier, is to run the script with cron and have the environment in the script.

扩展@carestad 示例,我发现它更容易,是使用 cron 运行脚本并在脚本中设置环境。

In crontab -e file:

在 crontab -e 文件中:

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

In cron_job.sh file:

在 cron_job.sh 文件中:

SHELL=/bin/bash

*/1 * * * * /Path/to/script/script.sh

Any command after the source of .bash_profile will have your environment as if you logged in.

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

回答by Marcos Pousada

Expanding on @Robert Brisita has just expand , also if you don't want to set up all the variables of the profile in the script, you can select the variables to export on the top of the script

Expanding on @Robert Brisita 刚刚 expand ,同样如果您不想在脚本中设置配置文件的所有变量,您可以在脚本顶部选择要导出的变量

In crontab -e file:

在 crontab -e 文件中:

#!/bin/bash
export JAVA_HOME=/path/to/jdk

some-other-command

In script.sh

在脚本.sh

$ sudo  crontab -e

回答by karlingen

For me I had to set the environment variable for a php application. I resloved it by adding the following code to my crontab.

对我来说,我必须为 php 应用程序设置环境变量。我通过将以下代码添加到我的 crontab 来重新喜欢它。

ENVIRONMENT_VAR=production

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

crontab:

定时任务:

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

and inside doSomethingWonderful.php I could get the environment value with:

在 doSomethingWonderful.php 中,我可以通过以下方式获取环境值:

%daily 00 12 \
    set -a; \
    . /path/to/file/containing/vars; \
    set +a; \
    /path/to/script/using/vars

I hope this helps!

我希望这有帮助!

回答by Saucier

Another way - inspired by this this answer- to "inject" variables is the following (fcron example):

另一种方法 - 受此答案启发- “注入”变量如下(fcron 示例):

su -s /bin/bash -c "set -a; \
                    . /path/to/nullmailer-vars; \
                    set +a; \
                    /usr/sbin/logcheck" logcheck

From help set:

来自help set

-a Mark variables which are modified or created for export.

Using + rather than - causes these flags to be turned off.

-a 标记为导出而修改或创建的变量。

使用 + 而不是 - 会导致这些标志被关闭。

So everything in between set -and set +gets exported to envand is then available for other scripts, etc. Without using setthe variables get sourced but live in setonly.

因此,介于set -和之间的所有内容set +都导出到env其他脚本,然后可用于其他脚本等。不使用set变量获取源代码但set仅存在于其中。

Aside from that it's also useful to pass variables when a program requires a non-root account to run but you'd need some variables inside that other user's environment. Below is an example passing in nullmailer vars to format the e-mail header:

除此之外,当程序需要非 root 帐户运行但您需要在其他用户的环境中使用一些变量时,传递变量也很有用。下面是一个传入 nullmailer vars 以格式化电子邮件标头的示例:

$ crontab -l
myvar="hi man"
* * * * * echo "$myvar. date is $(date)" >> /tmp/hello

回答by Augusto Destrero

Setting vars in /etc/environmentalso worked for me in Ubuntu. As of 12.04, variables in /etc/environmentare loaded for cron.

/etc/environment在 Ubuntu 中设置 vars也对我有用。从 12.04 开始,/etc/environment为 cron 加载了变量 in 。

回答by fedorqui 'SO stop harming'

Whatever you set in crontabwill be available in the cronjobs, both directly and using the variables in the scripts.

无论您设置什么,crontab都可以在 cronjobs 中直接使用和使用脚本中的变量。

Use them in the definition of the cronjob

在 cronjob 的定义中使用它们

You can configure crontabso that it sets variables that then the can cronjob use:

您可以配置crontab以便它设置变量,然后可以 cronjob 使用:

$ 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

Now the file /tmp/helloshows things like:

现在文件/tmp/hello显示如下内容:

$ crontab -l
myvar="hi man"
* * * * * /bin/bash /tmp/myscript.sh

Use them in the script run by cronjob

在 cronjob 运行的脚本中使用它们

You can configure crontabso that it sets variables that then the scripts can use:

您可以配置crontab以便它设置脚本可以使用的变量:

echo "Now is $(date). myvar=$myvar" >> /tmp/myoutput.res

And say script /tmp/myscript.shis like this:

并说脚本/tmp/myscript.sh是这样的:

$ 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
...

It generates a file /tmp/myoutput.resshowing:

它生成一个文件,/tmp/myoutput.res显示:

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

回答by Ilya Kharlamov

Instead of

代替

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

Use bash -l -c

使用 bash -l -c

##代码##