Where can I set environment variables that crontab will use?

后端 未结 17 1534
说谎
说谎 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:06

    You can also prepend your command with env to inject Environment variables like so:

    0 * * * *   env VARIABLE=VALUE /usr/bin/mycommand
    
    0 讨论(0)
  • 2020-11-22 06:06
    • Set Globally env
    sudo sh -c "echo MY_GLOBAL_ENV_TO_MY_CURRENT_DIR=$(pwd)" >> /etc/environment"
    
    • Add scheduled job to start a script
    crontab -e
    
      */5 * * * * sh -c "$MY_GLOBAL_ENV_TO_MY_CURRENT_DIR/start.sh"
    

    =)

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

    For me I had to specify path in my NodeJS file.

    // did not work!!!!!
    require('dotenv').config()
    

    instead

    // DID WORK!!
    require('dotenv').config({ path: '/full/custom/path/to/your/.env' })
    
    0 讨论(0)
  • 2020-11-22 06:08

    Setting vars in /etc/environment also worked for me in Ubuntu. As of 12.04, variables in /etc/environment are loaded for cron.

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

    If you start the scripts you are executing through cron with:

    #!/bin/bash -l
    

    They should pick up your ~/.bash_profile environment variables

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

    I'm using Oh-my-zsh in my macbook so I've tried many things to get the crontab task runs but finally, my solution was prepending the .zshrc before the command to run.

    */30 * * * * . $HOME/.zshrc; node /path/for/my_script.js
    

    This task runs every 30 minutes and uses .zshrc profile to execute my node command.

    Don't forget to use the dot before the $HOME var.

    0 讨论(0)
提交回复
热议问题