Bash Automation & Scripting Skill
Workflows für Shell-Scripting, Automatisierung, Parsing, CI-Tooling.
Robuste Scripts
Template
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
# Config
VERSION="1.0.0"
LOG_FILE="/tmp/script.log"
# Colors
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
info() { echo -e "${GREEN}[✓]${NC} $*"; }
warn() { echo -e "${YELLOW}[!]${NC} $*"; }
error() { echo -e "${RED}[✗]${NC} $*" >&2; exit 1; }
# Usage
usage() {
cat <<EOF
Usage: $(basename "$0") [options]
Options:
-h, --help Show help
-v, --verbose Verbose output
-o, --output Output file
EOF
exit 0
}
[[ $# -eq 0 ]] && usage
while [[ $# -gt 0 ]]; do
case $1 in
-h|--help) usage ;;
-v|--verbose) VERBOSE=1 ;;
-o|--output) OUTPUT="$2"; shift ;;
*) error "Unknown: $1" ;;
esac
shift
done
info "Starting..."
trap 'warn "Interrupted"; exit 1' INT TERM
trap 'info "Cleanup done"' EXIT
Error Handling
# Run with timeout
timeout 30 command || { error "Command timed out"; }
# Retry loop
for i in {1..3}; do
command && break || sleep $((i * 2))
done
# Log everything
exec 1> >(tee -a "$LOG_FILE") 2>&1
Parsing Patterns
JSON mit jq
# API Response parsen
curl -s https://api.example.com/data | jq -r '
.items[] | select(.status == "active") | {name, id, created}
'
# CSV → JSON
jq -R 'split(",") | {name: .[0], age: .[1] | tonumber}' < data.csv | jq -s
YAML mit yq
# Config lesen
yq '.services.web.image' docker-compose.yml
# Value setzen
yq -i '.version = "2.0"' config.yaml
Docker Automation
# Bulk cleanup
docker ps -aq --filter "status=exited" | xargs -r docker rm
docker images -q --filter "dangling=true" | xargs -r docker rmi
# Bulk exec
for c in $(docker ps -q --filter "name=web"); do
docker exec "$c" kill -USR2 1 # reload
done
# Healthcheck loop
until curl -sf http://localhost:8080/health; do
echo "Waiting..."; sleep 2
done
info "Service ready"
Git Automation
# Bulk branch cleanup
git branch --merged main | grep -v "main\|*" | xargs -r git branch -d
# Auto-commit
git add -A && git commit -m "chore: auto-update $(date +%Y-%m-%d)" || true
# Status for all repos
for d in ~/projects/*/; do
(cd "$d" && echo "=== $d ===" && git status -s)
done
CI Helper Functions
# Semantic Version from Git
git_describe_version() {
local tag=$(git describe --tags --abbrev=0 2>/dev/null || echo "0.0.0")
local commit=$(git rev-list --count HEAD 2>/dev/null || echo "0")
echo "${tag}-build.${commit}"
}
# Check if CI
is_ci() {
[ -n "${CI:-}" ] || [ -n "${GITHUB_ACTIONS:-}" ] || [ -n "${GITLAB_CI:-}" ]
}
# Parallel execution
run_parallel() {
local pids=()
for cmd in "$@"; do
(eval "$cmd") &
pids+=($!)
done
for pid in "${pids[@]}"; do wait "$pid"; done
}