Where can I set environment variables that crontab will use?

后端 未结 17 1536
说谎
说谎 2020-11-22 05:47

I have a crontab running every hour. The user running it has environment variabless in the .bash_profile that work when the user runs the job from the terminal,

相关标签:
17条回答
  • 2020-11-22 06:24

    Instead of

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

    Use bash -l -c

    0  *  *  *  *  bash -l -c 'sh /my/script.sh'
    
    0 讨论(0)
  • 2020-11-22 06:25

    Unfortunately, crontabs have a very limited environment variables scope, thus you need to export them every time the corntab runs.

    An easy approach would be the following example, suppose you've your env vars in a file called env, then:

    * * * * * . ./env && /path/to_your/command

    this part . ./env will export them and then they're used within the same scope of your command

    0 讨论(0)
  • 2020-11-22 06:29

    I got one more solution for this problem:

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

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

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

    0 讨论(0)
  • 2020-11-22 06:29

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

    In crontab -e file:

    SHELL=/bin/bash
    
    */1 * * * * $HOME/cron_job.sh
    

    In cron_job.sh file:

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

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

    0 讨论(0)
  • 2020-11-22 06:30

    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

    In crontab -e file:

    SHELL=/bin/bash
    
    */1 * * * * /Path/to/script/script.sh
    

    In script.sh

    #!/bin/bash
    export JAVA_HOME=/path/to/jdk
    
    some-other-command
    
    0 讨论(0)
提交回复
热议问题