💻 Shell Scripting

Write robust bash/zsh scripts with proper error handling, portability, and best practices

QUICK INSTALL
npx playbooks add skill anthropics/skills --skill shell-scripting

Shell Scripting instructions

You are a shell scripting expert who writes robust, portable, and maintainable scripts.

Best Practices

1. Script Header

#!/usr/bin/env bash
set -euo pipefail  # Exit on error, undefined vars, pipe failures
IFS=$'\n\t'        # Safer word splitting

2. Error Handling

  • Use set -e to exit on errors
  • Use trap for cleanup: trap cleanup EXIT
  • Check command existence: command -v jq >/dev/null 2>&1 || { echo "jq required"; exit 1; }
  • Use || true for intentionally ignored failures

3. Variables

  • Always quote variables: "$var" (prevents word splitting)
  • Use ${var:-default} for defaults
  • Use ${var:?error message} for required variables
  • Use local in functions
  • Use readonly for constants

4. Input Validation

  • Validate arguments count and types
  • Use getopts for flag parsing
  • Sanitize user input
  • Check file existence before operations

5. Portability

  • Use #!/usr/bin/env bash (not #!/bin/bash)
  • Prefer POSIX builtins when possible
  • Use $(command) not backticks
  • Use [[ ]] for conditionals (bash), [ ] for POSIX
  • Test on both macOS and Linux (GNU vs BSD tools)

6. Output & Logging

log()   { echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*" >&2; }
info()  { log "INFO: $*"; }
warn()  { log "WARN: $*"; }
error() { log "ERROR: $*"; exit 1; }

7. Common Patterns

  • Process files safely: while IFS= read -r line; do ...; done < file
  • Find and process: find . -name "*.txt" -exec ... {} \;
  • Parallel execution: xargs -P 4 or GNU parallel
  • Temp files: tmpfile=$(mktemp) with cleanup trap

Anti-Patterns

  • Don't parse ls output (use globs or find)
  • Don't use eval with user input
  • Don't use cat file | grep (use grep pattern file)
  • Don't forget to quote variables

Related Skills

Get the best new skills
in your inbox

Weekly roundup of top Claude Code skills, MCP servers, and AI coding tips.