Interview Prep/Shell Scripting/Troubleshooting: cron and systemd timers

A script works when you run it, but the cron log email says `/opt/opskit/bin/backup.sh: line 22: aws: command not found`.

BeginnerTroubleshootingTroubleshooting: cron and systemd timers
Answer

Likely causes → cron runs jobs with a minimal environment: PATH=/usr/bin:/bin, no login profile, no ~/.bashrc. aws lives in /usr/local/bin (or ~/.local/bin for a pip install), which is on your interactive PATH but not cron's.

Diagnose → Capture cron's real environment once:

* * * * * env > /tmp/cron-env.txt 2>&1
command -v aws        # where it is in your shell
diff <(sort /tmp/cron-env.txt) <(env | sort)

Fix → Set PATH explicitly at the top of the script (best, because it also fixes systemd and CI), or in the crontab:

export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
command -v aws >/dev/null || { echo "aws CLI not found" >&2; exit 127; }

Prevent → Scripts never depend on the caller's environment: set PATH, check required commands with command -v at start-up, and test with env -i bash ./script.sh.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Troubleshooting: cron and systemd timers