Bash Scripting for Operators
Bash appears throughout this library in examples. This page collects patterns that reduce surprises in ops scripts: fail fast, quote variables, and avoid parsing ls. For Git, see Git essentials.
Shebang and Strict Mode
Section titled “Shebang and Strict Mode”#!/usr/bin/env bashset -euo pipefailIFS=$'\n\t'| Option | Effect |
|---|---|
set -e | Exit on first command that returns non-zero (with caveats in conditionals — use if cmd; then or cmd || true when intentional). |
set -u | Treat unset variables as error. |
set -o pipefail | Pipeline fails if any stage fails, not only the last. |
Variables and Quoting
Section titled “Variables and Quoting”name="prod-vpc"echo "Using ${name}"Always quote expansions unless you rely on word splitting: "$var" not $var. Paths and ARNs almost always need quotes.
Functions and Args
Section titled “Functions and Args”deploy_stack() { local region="$1" local stack="$2" aws cloudformation deploy --region "$region" --stack-name "$stack" ...}
deploy_stack "us-east-1" "my-network"Use local inside functions to avoid leaking names into the global script scope.
Running Other Tools
Section titled “Running Other Tools”terraform -chdir=envs/prod plan -out=tfplankubectl get pods -n "$NS"Capture output:
vpc_id=$(aws ec2 describe-vpcs --filters "Name=tag:Name,Values=main" --query 'Vpcs[0].VpcId' --output text)Check exit codes explicitly for critical steps:
if ! terraform apply tfplan; then echo "Apply failed" >&2 exit 1fiDebugging
Section titled “Debugging”set -x # trace (verbose; remove before committing secrets)Combine with set +x to limit trace to a section. Never log tokens or passwords.
Portability
Section titled “Portability”This site’s examples target bash on Linux and macOS. For POSIX sh only, avoid [[ ]], arrays, and some echo flags — use shellcheck to lint scripts.
Summary
Section titled “Summary”Strict mode + quoting + explicit error handling keeps glue scripts from corrupting state. For larger automation, prefer Ansible or Terraform over growing Bash programs.