Linux / Bash
Beginner
1 min read
Bash Functions, Error Handling, and Best Practices
Example
#!/bin/bash
set -euo pipefail
# ---- Logging helper ----
LOG_FILE="/var/log/deploy.log"
log() {
local level="$1"
local message="$2"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $message" | tee -a "$LOG_FILE"
}
# ---- Cleanup trap ----
TMPDIR=$(mktemp -d)
cleanup() {
log "INFO" "Cleaning up temporary files in $TMPDIR"
rm -rf "$TMPDIR"
}
trap cleanup EXIT
trap 'log "ERROR" "Script interrupted"; exit 1' INT TERM
# ---- Input validation function ----
validate_args() {
if [[ $# -lt 2 ]]; then
log "ERROR" "Usage: $0 <environment> <version>"
exit 1
fi
local env="$1"
if [[ ! "$env" =~ ^(staging|production)$ ]]; then
log "ERROR" "Environment must be 'staging' or 'production'"
exit 1
fi
}
# ---- Retry function ----
retry() {
local attempts="$1"
shift
local cmd=("$@")
local i
for (( i=1; i<=attempts; i++ )); do
if "${cmd[@]}"; then
return 0
fi
log "WARN" "Attempt $i/$attempts failed. Retrying..."
sleep 2
done
log "ERROR" "Command failed after $attempts attempts: ${cmd[*]}"
return 1
}
# ---- Main function ----
main() {
validate_args "$@"
local ENV="$1"
local VERSION="$2"
log "INFO" "Starting deployment of version $VERSION to $ENV"
retry 3 curl -sf "https://api.example.com/health"
log "INFO" "Deployment complete"
}
main "$@"
Related Resources
Linux / Bash Reference
Complete tag & property list
Linux / Bash How-To Guides
Step-by-step practical guides
Linux / Bash Exercises
Practice what you've learned
More in Linux / Bash