When issues arise using
cron to schedule events, a frequently-heard explanation is that
cron runs with a different set of environment variables than a "normal" user (e.g.
pi). That's all well and good, but what is the environment for the
cron user? If one is to avoid errors due to an incorrect environment when using
cron, it would be useful to know what that environment is.
When issues arise using
We can ask
cron to tell us what its environment is.
- Create a shell script in your home directory (
~/) as follows (or with the editor of your choice):
$ nano ~/envtst.sh
- Enter/C+P the following in the editor:
#!/bin/sh echo "env report follows for user "$USER >> /home/pi/envtst.sh.out env >> /home/pi/envtst.sh.out echo "env report for user "$USER" concluded" >> /home/pi/envtst.sh.out echo " " >> /home/pi/envtst.sh.out
- Save the file and exit the editor; then set the file permissions as executable, and open your
$ chmod a+rx ~/envtst.sh $ crontab -e
- Enter the following line at the bottom of your
* * * * * /home/pi/envtst.sh >> /home/pi/envtst.sh.err 2>&1
- Save and exit your
tailto view the output & (hopefully) observe the environment for
cron. If there's nothing in the file after a minute, view the file
~/envtst.sh.errfor error messages, and adjust as required. (NOTE: If you want to clear all prior error messages after troubleshooting:
$ > ~/envtst.sh.err)
crontab: installing new crontab $ tail -f ~/envtst.sh.out env report follows for user HOME=/home/pi LOGNAME=pi PATH=/usr/bin:/bin LANG=en_GB.UTF-8 SHELL=/bin/sh PWD=/home/pi env report for user concluded
This will repeat every minute, so enter
^C to stop the
tail listing, edit your
crontab again to "comment out" (or delete) the line just added. Save and exit the editor.
Note in the
tailoutput above that
cronhas a rather sparse environment; only six (6) variables are used to define it. Note the
PATHconsists of only two directories. This is why your crontab entry fails if, for example, you're trying to launch a Python script that resides in your home directory. Note also that the user name (aka LOGNAME iaw System V) isn't
If you're not familiar, with your own user environment, it's useful to compare it against the
cronenvironment. We'll use the same shell script to add that to the "output" file
$ ~/envtst.sh $
- To view the output, open
~/envtst.sh.outin your editor, or
cat ~/envtst.sh.outto see it in your terminal. It will likely be a fairly extensive output; 30 lines of text, more or less. Note in particular the following lines (assuming you've run this as user
USER=pi ... HOME=/home/pi LOGNAME=pi _=/home/pi/envtst.sh ... PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games ... SHELL=/bin/bash
- You'll notice numerous differences in the two environments. This will help create rational
cronjobs, and help troubleshooting when they don't behave as you'd like.