Code-Memo

Functions and script structuring

Why structure matters

Well-structured scripts are easier to test, reuse, and debug.

Function basics (Bash)

log() { printf '[%s] %s\n' "$(date -Is)" "$*" >&2; }

do_work() {
  local input="$1"
  log "processing: $input"
}

Notes

main() pattern

main() {
  [[ $# -ge 1 ]] || { echo "Usage: $0 <path>" >&2; exit 2; }
  do_work "$1"
}
main "$@"

Files and layout (suggestion)

Error handling patterns

Guard clauses

[[ -d "$dir" ]] || { echo "Not a dir: $dir" >&2; exit 2; }

Cleanup with trap

tmp="$(mktemp -d)"
cleanup() { rm -rf "$tmp"; }
trap cleanup EXIT