>_ IzzyLab

Hands-on task

This task is step 28 of the course “Bash scripts: from a loop to a robust script”

Fix PATH for a cron job

medium~7 min

Cron runs jobs with a minimal environment (PATH=/usr/bin:/bin), so /opt/deploy.sh can't find the deployctl utility and fails. Without touching the script itself, set the PATH variable in the root crontab to include /usr/local/bin:/usr/bin:/bin, and add an hourly run of /opt/deploy.sh (at the top of every hour).

The job must work when run the way cron runs it — with an empty environment and only the variables from the crontab. A successful run appends a deployed … line to /var/log/deploy.log.

What you'll practise:
  • cron
  • environment variables
  • PATH
  • crontab

Topic breakdown

Cron runs jobs with a stripped-down environment, so variables familiar in an interactive shell often end up empty — hence "can't find the binaries". In the crontab file itself you can declare environment variables with lines of the form NAME=value; placed above the jobs, they apply to all lines below. The idea of the solution is to set the required PATH with such a line and then add a regular schedule entry; the finished list is loaded via standard input (crontab -).

What's checked

  1. PATH set in the crontab above the job
  2. hourly run of deploy.sh
  3. the crontab job works in cron's environment

What it looks like