问题
I'v hit a brick wall with crontab... I'm trying to set a crontab to run a python script that gathers 4 variables from ~/.bashrc
Bellow my current crontab.
SHELL=/bin/bash
BASH_ENV=/home/m.bienias/.bashrc
# m h dom mon dow command
30 12,15,18 * * 1,2,3,4,5 source /home/m.bienias/.bashrc; /usr/bin/python3
/home/m.bienias/skrypty/mail_reporter/Kwanty_bez_eng.py >> /home/m.bienias/cron-log/mail_reporter.log 2>&1```
I have tried ```source /home/m.bienias/.bashrc;``` and ```. /home/m.bienias/.bashrc;```
Any idea what more I've could miss. Please note that I'm not sudo user on the machine where I try do run crontab
回答1:
I would recommend creating a specific start wrapper script for your job.
Name the script something like run-Kwanty_bez_eng.sh
and store it inside /home/m.bienias/skrypty/mail_reporter/
This script is responsible for setting the environment and starting the job, so rough contents would be like:
#!/usr/bin/env bash
# set environment
source /home/m.bienias/.bashrc
# start job
/usr/bin/python3 /home/m.bienias/skrypty/mail_reporter/Kwanty_bez_eng.py
... this ultimately allows you greater control of the environment and even error handling.
I would further recommend to decouple the reliance on the .bashrc
and your job. The problem that can arise by having the job depend on .bashrc
is that changes to .bashrc
can cause the job to fail or behave incorrectly, and .bashrc
is a busy file in terms of responsibilities it serves. So better to build a job-specific environment file that contains only the minimum required variables to execute the job.
回答2:
You can create a cron job under /etc/cron.d like this:
SHELL=/usr/local/bin
PATH=/usr/local/sbin:/usr/local/bin/ <continues your PATH>
30 12,15,18 * * 1,2,3,4,5 root export VAR1=value1 && export VAR2=value2 && export VAR3=value3 && export VAR4=value4 /usr/bin/python3 /path_to_script/Kwanty_bez_eng.py
This way, I think that it prevent reload environment variables from shell profile via cron job when you will make some configuration in your shell profile.
The shell script to fire the python script, the most elegant way, can export the variables that you need although make source all .bashrc.
If you prefer create via crontab -e, like appear, it the same, just without user ahead of commands.
来源:https://stackoverflow.com/questions/58724798/crontab-passing-environment-variables-from-bashrc