Shell Scripting for Ops
Write robust Bash scripts for provisioning, entrypoints and CI steps that fail loudly and are safe to re-run.
Beginner · about 10 hours · difficulty 2/5
Learn first: Linux Command Line and Packages
Even if Python is your main language, you will read and write shell scripts constantly: Dockerfile entrypoints, CI steps, bootstrap scripts and one-off fixes. The goal is scripts that are safe, idempotent and readable.
Building blocks
- Shebang
#!/usr/bin/env bashand strict modeset -euo pipefail. - Always quote expansions:
"$var","$@". - Test conditions with
[[ ... ]], check commands withcommand -v, compare exit codes with$?. - Functions with
localvariables, and amainfunction called at the bottom. trap cleanup EXITfor temp files created withmktemp.- Here-docs for generating config files.
Idempotency
A script that provisions a server should be safe to run twice: check before creating (mkdir -p, id user || useradd user), and prefer declarative tools once logic grows.
JSON in the shell
jq is essential for reading API responses and cloud CLI output, for example aws ec2 describe-instances | jq -r '.Reservations[].Instances[].InstanceId'.
Pitfalls
Parsing ls output, silent failures in pipelines without pipefail, and scripts that only work from one directory (use cd "$(dirname "$0")").
Good enough to move on: you can write a re-runnable bootstrap script with logging, argument parsing and cleanup that passes ShellCheck.
Key concepts
- Strict mode and quoting
- Conditionals, loops and functions
- Exit codes and error handling
- trap and mktemp
- Idempotent scripts
- jq for JSON
- cron scheduling
Mini project
Write a bootstrap.sh that creates a user, installs packages, writes a config from a here-doc and enables a service; run it twice on the same VM and prove the second run changes nothing.
Check yourself
Without set -o pipefail, what exit code does false | true return, and why does that matter in CI?
Free resources
- GNU Bash Reference Manual (GNU)
- jq manual (jqlang)
- ShellCheck (shellcheck.net)