Skip to content

Bash Scripting for Operators

First PublishedByAtif Alam

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.

#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
OptionEffect
set -eExit on first command that returns non-zero (with caveats in conditionals — use if cmd; then or cmd || true when intentional).
set -uTreat unset variables as error.
set -o pipefailPipeline fails if any stage fails, not only the last.
Terminal window
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.

Terminal window
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.

Terminal window
terraform -chdir=envs/prod plan -out=tfplan
kubectl get pods -n "$NS"

Capture output:

Terminal window
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:

Terminal window
if ! terraform apply tfplan; then
echo "Apply failed" >&2
exit 1
fi
Terminal window
set -x # trace (verbose; remove before committing secrets)

Combine with set +x to limit trace to a section. Never log tokens or passwords.

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.

Strict mode + quoting + explicit error handling keeps glue scripts from corrupting state. For larger automation, prefer Ansible or Terraform over growing Bash programs.