Cron作业不会获取.bashrc中设置的环境变量

Pet*_*Lee 22 bash cron environment-variables

这是我的cron工作:

plee@dragon:~$ crontab -l
* * * * * /bin/bash -l -c 'source ~/.bashrc; echo $EDITOR > /tmp/cronjob.test'
Run Code Online (Sandbox Code Playgroud)

和内部~/.bashrc文件,我有export EDITOR=vim,但在最终/tmp/cronjob.test文件中,它仍然是空的?

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

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
Run Code Online (Sandbox Code Playgroud)

如果使用这个:

* * * * * /bin/bash -l -c -x 'source ~/.bashrc; echo $EDITOR > /tmp/cronjob.test' 2> /tmp/cron.debug.res
Run Code Online (Sandbox Code Playgroud)

/tmp/cron.debug.res:

...
++ return 0
+ source /home/plee/.bashrc
++ '[' -z '' ']'
++ return
+ echo
Run Code Online (Sandbox Code Playgroud)

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

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

source .bashrc; echo $EDITOR # Output: vim
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 44

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

# If not running interactively, don't do anything
[ -z "$PS1" ] && return
Run Code Online (Sandbox Code Playgroud)

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

+ source /home/plee/.bashrc
++ '[' -z '' ']'
++ return
Run Code Online (Sandbox Code Playgroud)

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

#[ -z "$PS1" ] && return
Run Code Online (Sandbox Code Playgroud)

这将使bash执行~/.bashrcvia 的全部内容cron

  • 或者在`source`ing` .bashrc`文件之前将`$ PS1`设置为某个任意值; 这样你就不必改变`.bashrc`. (8认同)
  • 这对我有用——我不知道为什么要这样设置,但在尝试其他东西几个小时后,它似乎已经成功了! (2认同)

vdu*_*dua 9

@alex提供的答案是正确的,但在Ubuntu 13.10中,代码已被修改了一点.没有$ PS1变量,但在第6-9行中有一个代码

case $- in 
   *i*) ;;       
   *) return;; 
esac
Run Code Online (Sandbox Code Playgroud)

只是评论返回工作的行.即下面的代码工作

case $- in 
   *i*) ;;       
#   *) return;; 
esac
Run Code Online (Sandbox Code Playgroud)

  • 如果您不需要此功能,请删除整个“case”语句。 (2认同)