shBash
AdvancedLesson 14 of 15

Script Best Practices & Portability – Bash

Robust, maintainable scripts: template, quoting, ShellCheck and the limits of Bash.

A solid template for scripts that are meant to live longer than a throwaway command. It combines strict mode, script directory, log functions, cleanup and a main function:

#!/usr/bin/env bash
#
# backup.sh – backs up a folder as tar.gz
# Usage: backup.sh <source-folder> [target-folder]
set -euo pipefail
IFS=$'\n\t'

readonly SKRIPT_NAME="${0##*/}"
readonly SKRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

log()  { printf '%s [%s] %s\n' "$(date +%F' '%T)" "$SKRIPT_NAME" "$*" >&2; }
fehler() { log "ERROR: $*"; exit 1; }

main() {
  [[ $# -ge 1 ]] || fehler "Usage: $SKRIPT_NAME <source-folder> [target-folder]"
  local quelle="$1" ziel="${2:-.}"
  [[ -d "$quelle" ]] || fehler "Source not found: $quelle"
  local archiv="$ziel/backup-$(date +%Y%m%d-%H%M%S).tar.gz"
  tar -czf "$archiv" -C "$(dirname "$quelle")" "$(basename "$quelle")"
  log "Backup created: $archiv"
}

main "$@"
  • Quote everything: "$var", "$(command)", "$@" – exceptions are places inside [[ ]] and assignments (x=$y is safe).
  • Run ShellCheck (editor, pre-commit, CI). It knows the most common error patterns (SC2086 = missing quotes).
  • Create temporary files with mktemp and delete them via trap ... EXIT – never fixed names like /tmp/daten.
  • Dry-run option (--dry-run) for everything that deletes or modifies.
  • Check dependencies: command -v jq >/dev/null || fehler "jq missing".
  • Guard dangerous variables: rm -rf "${ziel:?}/" aborts if ziel were empty.

Portability: #!/bin/sh means a POSIX shell (on Debian/Ubuntu that is dash – no [[ ]], no arrays!). If you want Bash features, write #!/usr/bin/env bash. Differences between macOS (BSD tools, Bash 3.2, zsh as the default shell) and Linux (GNU tools) affect sed -i, date -d, readlink -f, grep -P, xargs -r, stat and sort -V.

# detect the operating system and adapt commands
case "$(uname -s)" in
  Darwin) sed_inplace() { sed -i '' "$@"; } ;;
  Linux)  sed_inplace() { sed -i "$@"; } ;;
  *)      echo "Unknown system" >&2; exit 1 ;;
esac
sed_inplace 's/alt/neu/' datei.txt

# check the version when Bash 4 features are needed
(( BASH_VERSINFO[0] >= 4 )) || { echo "Bash >= 4 required" >&2; exit 1; }
WarningIf a script becomes complex (nested data, lots of error logic, parallelism, tests), switch languages. Rule of thumb: beyond ~100 lines, JSON processing or data structures, Python or Go are the better choice – Bash remains the glue.
TipNever put user input unchecked into eval, bash -c or command strings – that is command injection. Instead, pass arguments as an array: befehl=(grep -i -- "$muster" datei); "${befehl[@]}".