Dev Notes

Various Cheat Sheets and Resources by David Egan/Carawebs.

Access $USER Environment Variable in a Cron Triggered Script in Ubuntu


BASH, Linux
David Egan

When triggering a BASH script in a Cronjob in Ubuntu the script will not have access to the $USER environment variable.

This is the case even if the script is trigerred by the user’s crontab. Fortunately this is easily fixed.

Within the crontab, $LOGNAME represents the current user - so you can set the $USER variable before calling your script:

# Open the crontab for your user:
crontab -e

# Sample cron job:
# m h  dom mon dow   command
05 17 * * * env USER=$LOGNAME /usr/local/bin/backup-home

…you can now use $USER in the script as usual.

Background

Several environment variables are set automatically by cron:

  • SHELL: is set to /bin/sh
  • LOGNAME: is set from the line in /etc/passwd corresponding to the crontab’s owner
  • HOME: is set from the line in /etc/passwd corresponding to the crontab’s owner

Note that HOME and SHELL can be overridden in the crontab but LOGNAME cannot.

References


comments powered by Disqus