iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Examples

A handful of bash patterns you reach for weekly - log rotation, csv loop, find + xargs, parallel.

Bash by example

EXAMPLE
#!/usr/bin/env bash
set -Eeuo pipefail
IFS=$'\n\t'

# 1. CSV loop with header skip
{
  read -r _header
  while IFS=, read -r id name email; do
    printf 'hello %s <%s> (id=%s)\n' "$name" "$email" "$id"
  done
} < users.csv


# 2. find + xargs - safe with NUL separator
find /var/log/myapp -type f -name '*.log' -mtime +14 -print0 \
  | xargs -0 -I {} gzip --best {}


# 3. Parallel by N
# Compress 8 in parallel
find /backup -name '*.tar' -print0 \
  | xargs -0 -n1 -P8 gzip


# 4. Atomic write via temp + mv
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT

curl -sSf https://example.com/api/feed.json | jq '.' > "$tmp"
mv "$tmp" /var/lib/myapp/feed.json   # atomic on same FS


# 5. Retry with exponential backoff
retry() {
  local max=$1 delay=1 i
  shift
  for ((i=1; i<=max; i++)); do
    if "$@"; then return 0; fi
    if (( i < max )); then sleep $delay; delay=$((delay*2)); fi
  done
  return 1
}

retry 5 curl -fsS https://api.example.com/health


# 6. Run a block as another user
sudo -u app bash -c 'cd /opt/myapp && ./run.sh'


# 7. Print on error AND on exit
trap 'echo "failed at line $LINENO" >&2' ERR
trap 'echo "goodbye"' EXIT


# 8. Process substitution (no temp file)
diff <(jq -S . a.json) <(jq -S . b.json)


# 9. heredoc into a remote command
ssh prod 'bash -s' <<'EOF'
  set -Eeuo pipefail
  sudo systemctl restart myapp
  curl -fsS http://localhost:3000/healthz
EOF


# 10. Timestamped log helper
ts() { printf '[%s] %s\n' "$(date +%FT%T%z)" "$*"; }
ts 'deploy started'

Why it matters

These ten cover the lion share of glue scripts. Strict mode is the foundation; once you have it, retry-with-backoff and atomic write via mktemp turn brittle scripts into reliable ones.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
# Get total disk usage of current dir
du -sh .
# Top 10 biggest files
du -ah . | sort -hr | head
Try it Yourself »

Discussion

Loading…