Field Notes: Scripts That Run at 3 a.m.
Automation fails in ways that never show up when you run it by hand at your desk. These notes collect the failures that keep coming back, grouped by where they bite, each with the habit that prevents it.
"It works when I run it"
Scheduled and CI jobs run in a different environment from your interactive shell: no ~/.bashrc, a minimal PATH,
no HOME or USER in some contexts, no terminal, a different working directory and often a different user. A
script started with an empty environment shows what is really guaranteed:
cat > report.sh <<'SCRIPT'
#!/usr/bin/env bash
set -euo pipefail
echo "PATH=$PATH"
echo "HOME=${HOME:-<unset>} USER=${USER:-<unset>} TERM=${TERM:-<unset>}"
echo "cwd=$PWD"
echo "writing to ${REPORT_DIR:?REPORT_DIR must be set}"
SCRIPT
chmod +x report.sh
mkdir -p /tmp/elsewhere && cd /tmp/elsewhere
env -i /home/learner/report.sh; echo "-> status $?"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOME=<unset> USER=<unset> TERM=dumb
cwd=/tmp/elsewhere
/home/learner/report.sh: line 6: REPORT_DIR: REPORT_DIR must be set
-> status 1
With no environment at all, Bash falls back to its own compiled-in PATH and sets TERM=dumb; HOME and USER
are simply missing, and the script runs in whatever directory its caller was in.
- Set what you need explicitly at the top of the script or in the job definition:
PATH,LANG=C.UTF-8,TZ=UTC, and every config variable. Cron usesPATH=/usr/bin:/binby default, so tools in/usr/local/bin"disappear". - Never depend on the working directory. Use absolute paths, or
cd "$(dirname "$0")"at the start when the script works relative to its own location. - Fail early on missing configuration with
${VAR:?message}, as above, instead of halfway through. - Test the scheduled form: run it once with
env -i(orsystemd-run, or the CI job itself) before trusting it.
Line endings and invisible characters
A script edited on Windows or pasted from a chat tool may carry \r\n line endings or non-breaking spaces. Bash
reads the \r as part of each word, with baffling results:
printf '#!/usr/bin/env bash\nset -euo pipefail\ndir=releases\nmkdir -p "$dir"\necho "created $dir"\n' \
| sed 's/$/\r/' > deploy.sh # simulate a file saved with CRLF endings
bash deploy.sh 2>&1 | cat -v; echo "-> status ${PIPESTATUS[0]}"
echo "lines with a carriage return: $(grep -c