ubuntu, updated

Script best practices

A safe script template plus the habits that keep admin scripts reliable: strict mode, quoting, logging, locking and shellcheck.

A template to start from

#!/bin/bash
# Purpose: <what this script does>
# Usage:   myjob.sh <args>
# Runs as: <user>, via /etc/cron.d/myjob
set -euo pipefail

readonly LOG_FILE="/var/log/myjob.log"

log() { echo "$(date '+%F %T') $*" | tee -a "$LOG_FILE"; }
die() { log "ERROR: $*"; exit 1; }

# only one instance at a time
exec 9>/run/lock/myjob.lock
flock -n 9 || die "already running"

log "start"
# ... your commands ...
log "done"

The rules

1. Use strict mode: set -euo pipefail.

OptionEffect
-eStop at the first command that fails
-uStop when using an unset variable (catches typos like $BAKUP_DIR)
-o pipefailA pipeline fails if any part fails, not just the last

Without it, a failed cd /backup is ignored and the following rm -rf * runs in the wrong folder.

2. Quote every variable. "$FILE", not $FILE. Unquoted variables split on spaces and expand *.

3. Guard dangerous commands.

rm -rf "${TARGET_DIR:?not set}/"*     # aborts if TARGET_DIR is empty, instead of deleting /*

4. Use full paths in scripts for cron. Cron’s PATH is minimal. Either use full paths (/usr/bin/rsync) or set PATH= at the top of the script.

5. Log what happens. With a timestamp, to a file or the journal (logger -t myjob "message" writes to the journal; read it with journalctl -t myjob).

6. Exit with a meaningful code. 0 for success, non-zero for failure, so monitoring and cron can react.

7. Prevent overlapping runs with flock (see template), for jobs that may run longer than their interval.

8. Least privilege. Run as a dedicated service user, not root. See Cronjobs.

9. No secrets in the script. Read them from a file only the service user can read (chmod 600), e.g. source /etc/myjob/secrets.env.

10. Check before you run. Install shellcheck and fix what it reports. It catches most quoting and logic errors:

sudo apt install shellcheck
shellcheck myjob.sh

11. Test with a dry run. Add a --dry-run flag or echo in front of destructive commands the first time.

12. Keep scripts in Git. Header comment with purpose and usage, one script per task, and a place everyone knows (/usr/local/bin/, with the source in a repo).

When not to use Bash

Bash is great for gluing commands together. Once a script needs complex data handling (JSON, APIs, lots of logic) or grows beyond about 200 lines, switch to Python. For configuring many servers the same way, look at Ansible instead of scripts copied around.

Next: Example: backup script.

§ home
~/knubertus/home/
1,1 Top