正在加载,请稍候…

Bash Scripting: Automation, Error Handling, and Best Practices

Write reliable bash scripts — set -euo pipefail, trap, argument parsing, functions, arrays, and common automation patterns.

Bash Script Template

#!/usr/bin/env bash
set -euo pipefail  # Exit on error, undefined var, pipe failure

PORT="${PORT:-3000}"
DB_URL="${DATABASE_URL:?DATABASE_URL is required}"

TMP=""
cleanup() { [[ -n "$TMP" ]] && rm -f "$TMP"; }
trap cleanup EXIT
trap 'echo "Error at line $LINENO" >&2; exit 1' ERR

Functions + Logging

log() {
  local level="$1"; shift
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $*" >&2
}

process_file() {
  local file="$1"
  [[ ! -f "$file" ]] && { log "ERROR" "Not found: $file"; return 1; }
  TMP=$(mktemp)
  grep -v "^#" "$file" > "$TMP"
  mv "$TMP" "$file"
  log "INFO" "Processed: $file"
}

Argument Parsing

usage() { echo "Usage: $0 [-v] [-o DIR] file"; exit 1; }
VERBOSE=false; OUTPUT="./output"
while getopts "vo:h" opt; do
  case $opt in
    v) VERBOSE=true ;; o) OUTPUT="$OPTARG" ;; h|*) usage ;;
  esac
done
shift $((OPTIND-1))
INPUT="${1:?Input file required}"

Useful Patterns

# Parallel: process 4 files at a time
find . -name "*.log" | xargs -P 4 -I {} gzip {}

# Check dependency
command -v docker &>/dev/null || { echo "Docker required"; exit 1; }

# String operations
ext="${file##*.}"    # Get extension
base="${file%.*}"    # Remove extension

# Here-doc config
cat > /etc/app/config.yml <<EOF
port: ${PORT}
db: ${DB_URL}
EOF

-> Encode bash output with the Base64 Converter.