DevOps · Guide

Bash Scripting

Variables, loops, functions, error handling, automation.

— min read DevOps

Theory

Bash Scripting: Variables, loops, functions, error handling, automation.

Bash is the default shell on most Linux systems and macOS. A bash script is a text file starting with #!/bin/bash (the shebang) followed by shell commands. Make it executable with chmod +x script.sh and run it with ./script.sh or bash script.sh. Scripts run in a child shell — variables set inside don't affect the parent shell unless you source it: source script.sh or . script.sh.

Variables: name="Alice" (no spaces around =). Reference with $name or ${name}. Use double quotes around variable references to handle spaces: echo "$name". $0 is the script name, $1–$9 are positional arguments, $@ is all arguments as separate words, $# is the argument count, $? is the exit code of the last command (0 = success, non-zero = error).

Conditionals: if [ condition ]; then ... elif ...; else ...; fi. Common test operators: -f file (file exists), -d dir (directory exists), -z "$var" (string empty), -n "$var" (string non-empty), = for string equality, -eq/-lt/-gt for integer comparison. Use [[ ]] (double brackets) for extended tests — supports regex matching and avoids word-splitting bugs.

Loops: for item in list; do ... done. for i in $(seq 1 10) iterates 1–10. while [ condition ]; do ... done. Read a file line by line: while IFS= read -r line; do echo "$line"; done < file.txt. break exits the loop; continue skips to the next iteration.

Functions: my_func() { local var="local"; echo "$var"; }. Call with my_func arg1. local declares variables scoped to the function. Functions return an exit code (return 0 for success), not a value — capture output with result=$(my_func) or use a global variable.

Pipes and redirection: cmd1 | cmd2 pipes stdout of cmd1 to stdin of cmd2. > overwrites a file; >> appends. 2> redirects stderr; 2>&1 merges stderr into stdout. /dev/null discards output. Subshell: $(cmd) captures output as a string. Process substitution: diff <(cmd1) <(cmd2) compares outputs without temp files.

Error handling: set -e exits the script on any error (without it, scripts continue past failures silently). set -u treats unset variables as errors. set -o pipefail makes pipelines fail if any command in the pipe fails (without it, echo "bad" | false exits 0). Combine: set -euo pipefail at the top of every production script. Trap cleanup: trap 'rm -f /tmp/workfile' EXIT runs cleanup on exit or error.

Architecture Diagram

  Developer / CI job
         |
  bash script (set -euo pipefail)
         |
    +----+----+
    v         v
  CLI tools   log / metrics
  (curl, aws) (stdout, files)

Examples

bash
# Bash Scripting
# Variables, loops, functions, error handling, automation.
# Validate in staging before production rollout.

Interview Questions

What problem does Bash Scripting solve?

It addresses the core use case described in production architecture — map features to reliability, scale, or velocity outcomes.

Key components of Bash Scripting?

Identify inputs, outputs, control plane, data plane, and failure domains — interviewers want structured decomposition.

Common production pitfalls?

Misconfiguration, missing observability, no rollback path, and scaling bottlenecks under peak load.

How do you test changes safely?

Staging parity, canary/gradual rollout, automated health checks, and documented rollback.

Metrics to prove success?

Error rate, latency percentiles, throughput, cost, and toil reduction — pick one primary SLO.

Beginner vs advanced concern?

Beginners focus on setup; advanced teams focus on blast radius, security boundaries, and operability at 10× scale.

Best Practices

  • Treat Bash Scripting config as code with review and CI validation.
  • Define SLOs and dashboards before production cutover.
  • Document rollback and ownership for on-call.
  • Use least privilege for credentials.

Common Mistakes

  • Adopting Bash Scripting without measurable success criteria.
  • No staging environment mirroring production constraints.
  • Missing rollback path during incidents.
  • Undocumented on-call expectations.

Cheat Sheet

BashVariables, loops, functions, error handling, automation.
SLOService level objective
RollbackRevert to last known good
CanaryLimited blast-radius rollout
RunbookIncident steps

Practical Exercises

Bash Scripting sandbox

Stand up Bash Scripting locally or in free tier; document commands and failure recovery.

Failure drill

Introduce misconfiguration; practice detection and rollback under time limit.