[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: cronjob in user environment



On Sep 02 14:18 +0200, Steve S  wrote:
> Hi all,
> 
> I want to run a cronjob in a user's environment (i.e. as this user and
> not as root).
> 
> The script foo.sh to be run by cron on behalf of the a user (johndoe)
> needs some env vars (paths) from that user's ~/.bashrc. 
> 
> I read about several solutions:
> 
> 1) use su
> 
> If I try in the crontab
> 
>     10 12 * * */2   su -p - johndoe -c /home/johndoe/foo.sh
> 
> I get the message "su must be run from a terminal" in the cron mail.
> Hmm ...
> 
> 2) define env vars in the crontab
> 
> It works if I define the env vars as a full path
> 
>     $SOME_VAR=/full/path/1
>     $SOME_OTHER_VAR=/full/path/2
>     10 12 * * */2   su -p - johndoe -c /home/johndoe/foo.sh
> 
> In ~/.bashrc, I have 
>     
>     $SOME_VAR=$HOME/path/1
>     $SOME_OTHER_VAR=$HOME/path/2
> 
> and I'd rather not dublicate the definitions.

Thanks for all answers. Yes, I did use `crontab -e`. I also tried
sourcing .bashrc but it didn't expose the env vars defined in there (see
below), that's why I came up with (1) and (2) above.

One suggested solution

    10 12 * * */2   USER=johndoe /home/johndoe/foo.sh

does not work since it sets only USER but not all other env vars.

The cleanest solution seems to be

    10 12 * * */2   . $HOME/.bashrc.env /home/johndoe/foo.sh

where $HOME/.bashrc.env contains only export statements. The problem was
that my ~/.bashrc starts with 

    [ -z "$PS1" ] && return 

and so nothing happens if it's sourced. I had to put all exports into
this separate file b/c in .bashrc I have some shell function
definitions and scripts which source .bashrc don't like that. 

Sourcing .bashrc.env in foo.sh does also work. But foo.sh itself calls
other scripts which also need the env vars, so the first route is
easier.

Thanks everyone.

best,
steve


Reply to: