TExcelTAD
Home › Automation Scripting: Bash, Python & Go › Field Notes: Scripts That Run at 3 a.m.

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:

bash · try it yourself
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 uses PATH=/usr/bin:/bin by 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 (or systemd-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:

bash · try it yourself
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 
  

\r' deploy.sh)"
sed -i 's/\r$//' deploy.sh                           # or: dos2unix deploy.sh
bash deploy.sh
deploy.sh: line 2: set: pipefail^M: invalid option name
-> status 2
lines with a carriage return: 5
created releases

cat -v makes the \r visible as ^M. Prevent it at the source: a .gitattributes line *.sh text eol=lf, an .editorconfig with end_of_line = lf, and a CI check (grep -rl

#39;\r' --include='*.sh' . must find nothing).

Destructive commands

  • Guard variables in paths you delete. rm -rf "$BUILD_DIR/"* with an unset or empty BUILD_DIR deletes from /. Use "${BUILD_DIR:?}", set -u, and ShellCheck's SC2115 catches the pattern.
  • Make dry run the default for scripts that delete or modify many things, with an explicit --apply (Debugging and Dry Runs).
  • Print the scope before acting: "about to delete 1,204 snapshots in account prod-eu" stops more incidents than any amount of code review, especially when the number is unexpectedly large.
  • Put a limit on blast radius: refuse to act on more than N objects without --force, process one region or cluster at a time, and stop at the first failure.

Secrets

  • Pass secrets through environment variables or files with 600 permissions, never as command-line arguments: arguments are visible to every user in ps and often logged by CI.
  • Turn tracing off around secret-handling lines; set -x prints expanded values.
  • Do not echo "$TOKEN" | something in CI logs; most CI systems mask registered secrets, but not values derived from them (base64-encoded, URL-encoded, sliced).
  • curl -H "Authorization: Bearer $TOKEN" puts the token in the process list too; curl -H @headers-file or --config with a private file avoids it.

Portability traps

Trap Habit
macOS ships Bash 3.2 (no mapfile, no associative arrays, no ${var,,}) #!/usr/bin/env bash plus a Homebrew Bash, or write POSIX sh, or switch to Python/Go
BSD vs GNU tools: sed -i '' vs sed -i, date -d vs date -j, stat -c vs stat -f test on both, or use Python for date maths and file stats
echo -e and echo -n behave differently between shells use printf
/bin/sh is dash on Debian/Ubuntu a #!/bin/sh script must not use Bash features; ShellCheck tells you
locale-dependent sort, ls, [a-z] ranges LC_ALL=C for byte-wise, reproducible behaviour
Python version on servers differs from your laptop write for the oldest; check python3 --version in CI with the same base image

Operability

  • A script that fails silently is worse than no script. Make failures loud: non-zero exit status, a message on stderr, and an alert from whatever runs it (cron's MAILTO, a systemd OnFailure= unit, the CI system's notifications, a "dead man's switch" check that alerts when a heartbeat stops arriving).
  • Log what you changed, not just what you checked: "scaled shop-api from 2 to 4 replicas" is the line someone will grep for during an incident.
  • Make reruns safe: idempotent steps (Idempotent Scripts), a lock against overlapping runs (flock), and timeouts on everything that waits.
  • Put scripts in version control, with review, a README line per script, and the same lint as application code. "The script on the jump host" that nobody can find the source of is a classic incident root cause.
  • Pin what you download. curl https://…/install.sh | bash runs whatever that URL serves today. Download a versioned file, check its SHA-256 against a value committed in your repository, then run it.

Test yourself

A script works in your terminal but fails under cron with 'jq: command not found'. What is the most likely cause?

  1. jq is broken
  2. cron runs with a minimal PATH (often /usr/bin:/bin) and jq lives elsewhere, e.g. /usr/local/bin
  3. cron does not support pipes
  4. The script needs sudo

What causes set: pipefail^M: invalid option name?

  1. An old Bash version
  2. The script has Windows (CRLF) line endings, so each line ends with a carriage return
  3. pipefail is misspelt
  4. The script lacks a shebang

Why should secrets not be passed as command-line arguments?

  1. Arguments are limited to 8 characters
  2. Other users can see process arguments (e.g. with ps), and CI systems often log commands
  3. Bash cannot quote them
  4. They are slower than environment variables