Skip to main content...
Linux + Bash Scripting
30 min

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.

Variables and conditionals
#!/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
fi

Always 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.

Loops and pipes
for f in /var/log/*.log; do
  echo "Rotating $f"
  gzip "$f"
done

# Pipe: filter, then count
grep "ERROR" app.log | wc -l

Exit 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.

Checking exit codes
curl -sf https://example.com/health
if [[ $? -ne 0 ]]; then
  echo "Health check failed" >&2
  exit 1
fi

Key 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?

We use cookies

We use cookies to enhance your browsing experience, serve personalized content, and analyze our traffic. By clicking "Accept All", you consent to our use of cookies. Learn more

    Day 13: Bash scripting fundamentals | RBTechIconX