Cron job does NOT get the environment variables set in .bashrc

后端 未结 3 1609
误落风尘
误落风尘 2020-12-08 10:23

Here is my cron job:

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

and insi

相关标签:
3条回答
  • 2020-12-08 10:58

    I just tried a file .env_setup_rc file with only one line export EDITOR=vim, surprisingly it's working.

    So I guess there is something in .bashrc conflicting with the cron job bash command.

    0 讨论(0)
  • 2020-12-08 11:00

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

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

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

    This will make bash execute the entire contents of ~/.bashrc via cron

    0 讨论(0)
  • 2020-12-08 11:06

    Answer provided by @alex is correct but in Ubuntu 13.10 the code has been modified a little. There is no $PS1 variable but in lines 6-9 there is a code

    case $- in 
       *i*) ;;       
       *) return;; 
    esac
    

    Just commenting out the line which returns works. i.e. the code below works

    case $- in 
       *i*) ;;       
    #   *) return;; 
    esac
    
    0 讨论(0)
提交回复
热议问题