Day 13: Bash scripting fundamentals
Bash: turning manual steps into real automation
Every 'I always run these three commands in order' task should become a script. Bash's core building blocks: variables, conditionals, loops, pipes, and exit codes.
#!/usr/bin/env bash
set -euo pipefail # exit on error, undefined var, or failed pipe stage
ENVIRONMENT="${1:-staging}"
if [[ "$ENVIRONMENT" == "production" ]]; then
echo "Deploying to production — are you sure? (y/n)"
read -r confirm
[[ "$confirm" == "y" ]] || exit 1
fiAlways start scripts with `set -euo pipefail`
Without it, Bash silently continues after a failed command, an undefined variable expands to an empty string instead of erroring, and a failed command in the middle of a pipe is invisible. This one line prevents entire classes of "the script looked like it worked but didn't" bugs.
for f in /var/log/*.log; do
echo "Rotating $f"
gzip "$f"
done
# Pipe: filter, then count
grep "ERROR" app.log | wc -lExit codes
0 means success; anything else means failure, by convention. $? holds the exit code of the last command. This is exactly what CI pipelines (Phase 14) check to decide whether a step passed.
curl -sf https://example.com/health
if [[ $? -ne 0 ]]; then
echo "Health check failed" >&2
exit 1
fiKey terms
- set -euo pipefail
- A safety header that makes a Bash script fail loudly on errors instead of silently continuing.
- Exit code
- A number returned by a command; 0 = success, non-zero = failure by convention.
Why is `set -euo pipefail` recommended at the top of every Bash script?