Learn Cron

Cron provides only this environment by default :

MAILTO=”a@b.com,b@b.com”
PATH=”/usr/bin:/sbin:/bin” (get it from echo $PATH in the user login)
HOME=”/path/to/app/root”
SHELL=”/bin/bash”
LOGNAME user’s login

By default cron runs in sh shell

Export environment variables to file

30 08 * * * env > /tmp/cronenv

—————————–
Only /etc/crontab and the files in /etc/cron.d/ have a username field. In that file you can do this:

1 1 * * * username /path/to/your/script.sh
From root’s crontab sudo crontab -e you can use:

1 1 * * * su username -c “/path/to/your/script.sh”
Or you can use the user’s actual crontab like this:

sudo crontab -u username -e
—————————————————————
The following is an example on how to run a Django management command as the deploy user. You might notice that cron is run as root and then uses sudo to run as the deploy user with the argument -i. This is because we need to “simulate initial login” so that the source command works.:

0/5 * * * * root sudo -u deploy -i source /usr/local/virtualenvs/mysite/bin/activate && export DJANGO_SETTINGS_MODULE=config.settings && /usr/local/virtualenvs/mysite/bin/django-admin.py my_management_command

———————————————————————-

Schedule a script with error and output messages to a single file
* * * /bin/execute/this/script.sh >> /var/log/script_output.log 2>&1

 

—–
BASH_ENV=”/root/.bashrc

 

Cron tricks

https://blog.hazrulnizam.com/understanding-cron-environment-variables/
https://raymii.org/s/tutorials/Better_cron_env_and_shell_control_with_the_SHELL_variale.html
http://dev-notes.eu/2017/10/access-user-environment-variable-in-a-cron-triggered-script-in-ubuntu/
https://stackoverflow.com/questions/2135478/how-to-simulate-the-environment-cron-executes-a-script-with/2546509#2546509

https://www.endpoint.com/blog/2015/02/06/cron-wrapper-keep-your-cron-jobs

https://www.endpoint.com/blog/2013/05/28/login-shells-in-scripts-called-from-cron
https://bash.cyberciti.biz/guide/Source_command