Files
Jay Brown 451da3d26d Merged in feature/service-accounts-1 (pull request #227)
Support for service accounts with static credentials

* feature complete

* tests and docs

* lint fix
2026-05-21 19:40:04 +00:00

2.2 KiB

Bash Script Automation Rules

Error Handling

  • Always use set -euo pipefail at the top (exit on error, undefined vars, pipe failures)
  • Trap errors and cleanup: trap 'cleanup' EXIT ERR
  • Check command exit codes explicitly when needed: if ! command; then ... fi

Safety

  • Quote all variables: "$var" not $var
  • Use ${var:-default} for defaults, ${var:?error} for required vars
  • Validate inputs before destructive operations
  • Use absolute paths or verify working directory
  • Test with -n (dry-run) flag where possible
  • When script starts it should check that is has basic aws access if aws cli commands are being used. If we are not logged in then we should terminate and say why.

Idempotency

  • Make scripts safe to run multiple times with the same inputs
  • Check state before making changes: if [ ! -f file ]; then create; fi
  • Use atomic operations where possible

Logging & Debugging

  • Log to stderr for errors: echo "Error" >&2
  • Include timestamps: echo "[$(date +'%Y-%m-%d %H:%M:%S')] Message"
  • Add -x debug mode option: [[ "${DEBUG:-}" == "true" ]] && set -x
  • Log what the script is doing before doing it

Dependencies

  • Check for required commands at start: command -v tool >/dev/null || exit 1
  • Document external dependencies in comments
  • Fail fast if dependencies missing

Functions & Structure

  • Use functions for reusable logic
  • Keep functions small and single-purpose
  • Use local for function variables
  • Name functions with verbs: backup_database, verify_config
  • Each function should be clearly documented as to what it does and how it should be used.

Robustness

  • Use mktemp for temporary files, never hardcode /tmp/myfile
  • Handle signals: trap 'rm -f "$tmp_file"' EXIT
  • Avoid parsing ls output - use globs or find
  • Use [[ ]] instead of [ ] for tests

Configuration

  • Accept config via environment variables or config file unless otherwise instructed.
  • Provide sensible defaults

Exit Codes

  • Exit 0 only on complete success
  • Use distinct exit codes for different failures
  • Document exit codes in comments

Portability

  • Use #!/usr/bin/env bash not #!/bin/bash
  • Avoid bashisms if targeting sh, or explicitly require bash
  • Test on target platform