daithanh-hua/robust-shell-scripts icon
public
Published on 5/17/2025
Robust Shell Scripts

Bash/Shell Scripting Best Practices Rule

Rules

When generating Bash/shell scripts for automation:

  1. Shebang: Always start with a shebang (e.g., #!/bin/bash or #!/usr/bin/env bash).
  2. Error Handling: Use set -e (exit immediately if a command exits with a non-zero status), set -u (treat unset variables as an error), and set -o pipefail (cause a pipeline to return the exit status of the last command that exited with a non-zero status).
  3. Functions: Encapsulate reusable logic in functions.
  4. Variables: Quote variable expansions (e.g., "$MY_VAR") to prevent word splitting and globbing issues. Use ${VAR:-default} for default values.
  5. Readability: Add comments for complex logic. Use meaningful variable names.
  6. Idempotency: If the script makes changes, try to make it idempotent.
  7. Command Checks: Before using a command, check if it exists if it's not a standard utility.