Cron 作业没有获得在 .bashrc 中设置的环境变量 [英] Cron job does NOT get the environment variables set in .bashrc

查看:29
本文介绍了Cron 作业没有获得在 .bashrc 中设置的环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 cron 工作:

Here is my cron job:

plee@dragon:~$ crontab -l
* * * * * /bin/bash -l -c 'source ~/.bashrc; echo $EDITOR > /tmp/cronjob.test'

~/.bashrc 文件中,我有 export EDITOR=vim,但在最终的 /tmp/cronjob.test 文件中,还是空的?

and inside ~/.bashrc file, I have export EDITOR=vim, but in the final /tmp/cronjob.test file, it's still empty?

那么如何获取环境变量(在 .bashrc 文件中设置)并在我的 cron 作业中使用它?

So how can I get the environment variables (set in .bashrc file) and use it in my cron job?

plee@dragon:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 12.04 LTS
Release:        12.04
Codename:       precise
plee@dragon:~$ uname -a
Linux dragon 3.2.0-26-generic-pae #41-Ubuntu SMP Thu Jun 14 16:45:14 UTC 2012 i686 i686 i386 GNU/Linux

如果使用这个:

* * * * * /bin/bash -l -c -x 'source ~/.bashrc; echo $EDITOR > /tmp/cronjob.test' 2> /tmp/cron.debug.res

/tmp/cron.debug.res:

...
++ return 0
+ source /home/plee/.bashrc
++ '[' -z '' ']'
++ return
+ echo

顺便说一句,.bashrc 文件是 Ubuntu 12.04 附带的默认文件,除了我添加了一行 export EDITOR=vim.

BTW, the .bashrc file is the default one came with Ubuntu 12.04, with the exception that I added one line export EDITOR=vim.

如果我不使用 cron 作业,则直接在命令行上执行此操作:

If I don't use the cron job, instead, just directly do this on the command line:

source .bashrc; echo $EDITOR # Output: vim

推荐答案

source ~/.bashrc 不工作的原因是你的~/.bashrc 上的内容(默认来自 Ubuntu 12.04).如果您查看它,您将在第 5 行和第 6 行看到以下内容:

The reason for source ~/.bashrc not working is the contents on your ~/.bashrc (default one from Ubuntu 12.04). If you look in it you will see on lines 5 and 6 the following:

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

PS1 变量是为交互式 shell 设置的,因此在通过 cron 运行时它不存在,即使您将其作为登录 shell 执行也是如此.这由 /bin/bash -l -c -x 'source ~/.bashrc; 生成的文件的内容确认.回声 $EDITOR >/tmp/cronjob.test':

PS1 variable is set for an interactive shell, so it's absent when run via cron, even though you are executing it as a login shell. This is confirmed by contents of the file produced by /bin/bash -l -c -x 'source ~/.bashrc; echo $EDITOR > /tmp/cronjob.test':

+ source /home/plee/.bashrc
++ '[' -z '' ']'
++ return

要使 source ~/.bashrc 工作,请注释掉检查 ~/.bashrc 中是否存在 PS1 变量的行:

To make source ~/.bashrc work, comment out the line that checks for presence of the PS1 variable in ~/.bashrc:

#[ -z "$PS1" ] && return

这将使 bash 通过 cron

这篇关于Cron 作业没有获得在 .bashrc 中设置的环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆