snippetbashModeratepending
Bash script template — robust shell scripting boilerplate
Viewed 0 times
bash templatescript boilerplateargument parsinggetoptstrapstrict mode
terminallinuxmacos
Problem
Need a starting template for robust bash scripts with error handling, argument parsing, colored output, cleanup on exit, and help text.
Solution
Production-ready bash script template with strict mode, argument parsing, colored logging, trap cleanup, and usage text.
Code Snippets
Robust bash script template with error handling and arg parsing
#!/usr/bin/env bash
set -euo pipefail
# Colors
RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' NC='\033[0m'
log() { echo -e "${GREEN}[INFO]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*" >&2; }
err() { echo -e "${RED}[ERROR]${NC} $*" >&2; }
die() { err "$@"; exit 1; }
# Cleanup on exit
cleanup() { rm -f "$TMPFILE" 2>/dev/null || true; }
trap cleanup EXIT
TMPFILE=$(mktemp)
# Defaults
VERBOSE=false
OUTPUT=""
# Usage
usage() {
cat <<EOF
Usage: $(basename "$0") [OPTIONS] <input-file>
Options:
-o FILE Output file (default: stdout)
-v Verbose mode
-h Show this help
EOF
exit 0
}
# Parse args
while getopts ':o:vh' opt; do
case $opt in
o) OUTPUT="$OPTARG" ;;
v) VERBOSE=true ;;
h) usage ;;
:) die "Option -$OPTARG requires an argument" ;;
?) die "Unknown option -$OPTARG" ;;
esac
done
shift $((OPTIND - 1))
[[ $# -lt 1 ]] && die "Missing required argument. Use -h for help."
INPUT="$1"
[[ -f "$INPUT" ]] || die "File not found: $INPUT"
log "Processing $INPUT..."
$VERBOSE && log "Verbose mode enabled"Revisions (0)
No revisions yet.