All Modules Why Bash Basics Hands-on Lab Cheat Sheet

Bash Scripting

Turn commands you type once into automation you run forever.

Module 3 · Variables, conditionals, loops, functions — build a real script. Free · Local.

Beginner Foundations ~50 min

What You'll Learn

  • Write and run a Bash script (shebang, chmod +x, ./script.sh)
  • Use variables, command substitution, and quoting correctly
  • Make decisions with if and loops with for / while
  • Read arguments and write reusable functions
  • Build a practical backup script from scratch

Prerequisites: Module 2 (Linux) — you should be comfortable with basic commands.

Why Bash Scripting

A Bash script is just a text file full of the same commands you already type — saved so you can run them all at once, every time, identically. That's the very definition of automation, and it's where DevOps begins.

From typing to automating

Anything you do more than twice in the terminal is a candidate for a script: backups, deployments, log cleanup, environment setup. Scripts don't get tired, don't forget a step, and run in seconds.

You'll see Bash everywhere

Dockerfiles run shell commands. CI/CD pipelines (Module 9) are largely shell steps. Server setup is shell. Learning Bash now pays off in every later module.

The Building Blocks

Every script starts with a shebang

#!/usr/bin/env bash # the "shebang" — tells the OS to run this with bash echo "Hello, DevOps!"

Variables & substitution

name="Sam" # no spaces around = echo "Hi $name" # use $ to read it -> Hi Sam today=$(date +%F) # command substitution: capture a command's output echo "Today is $today"

Quote your variables

Always wrap variables in double quotes: "$name". Without quotes, a value with spaces breaks your script. This single habit prevents most beginner Bash bugs.

Hands-on Lab: Build a Backup Script

We'll build up a real, useful script piece by piece: it backs up a folder into a timestamped archive. Create a file backup.sh and follow along.

1

Your first runnable script

#!/usr/bin/env bash echo "Backup script starting..."

Make it executable and run it:

chmod +x backup.sh ./backup.sh
2

Add a safety header & variables

set -euo pipefail makes scripts fail fast instead of silently continuing after an error — a professional habit.

#!/usr/bin/env bash set -euo pipefail # exit on error, unset var, or pipe failure source_dir="$HOME/devops-practice" backup_dir="$HOME/backups" timestamp=$(date +%Y%m%d-%H%M%S)
3

Make a decision with if

Check the source exists before backing up; create the destination if missing.

if [ ! -d "$source_dir" ]; then echo "Error: $source_dir does not exist" exit 1 fi mkdir -p "$backup_dir" # -p: no error if it already exists

Common test flags

-d dir exists · -f file exists · -z string empty · -eq/-lt/-gt number equals/less/greater. Negate with !.

4

Do the work & report

archive="$backup_dir/backup-$timestamp.tar.gz" tar -czf "$archive" "$source_dir" echo "✅ Backed up to $archive"

Run ./backup.sh — you now have a timestamped archive in ~/backups. Run it again; you get a second one. That's automation.

5

Loop over many things

A for loop repeats work. Here's how you'd list each .tar.gz backup with its size:

for file in "$backup_dir"/*.tar.gz; do size=$(du -h "$file" | cut -f1) echo "$file — $size" done
6

Accept arguments

$1, $2… are the arguments passed to your script. Let the user choose the folder:

source_dir="${1:-$HOME/devops-practice}" # use $1 if given, else a default # now run: ./backup.sh ~/Documents

Special variables

$1 $2 args · $0 script name · $# number of args · $@ all args · $? exit code of last command.

7

Wrap it in a function

Functions keep scripts tidy and reusable:

log() { echo "[$(date +%T)] $1" } log "Starting backup" # ... do work ... log "Done"

You wrote a real tool

Variables, a safety header, a conditional, a loop, arguments, and a function — the same constructs power deployment and setup scripts everywhere in DevOps.

The Complete Script

Everything assembled:

#!/usr/bin/env bash set -euo pipefail log() { echo "[$(date +%T)] $1"; } source_dir="${1:-$HOME/devops-practice}" backup_dir="$HOME/backups" timestamp=$(date +%Y%m%d-%H%M%S) if [ ! -d "$source_dir" ]; then echo "Error: $source_dir does not exist" >&2 exit 1 fi mkdir -p "$backup_dir" archive="$backup_dir/backup-$timestamp.tar.gz" log "Backing up $source_dir" tar -czf "$archive" "$source_dir" log "✅ Done: $archive"

Bash Cheat Sheet

SyntaxWhat it does
#!/usr/bin/env bashShebang — first line of every script
set -euo pipefailFail fast on errors (use it always)
name="value"Set a variable (no spaces around =)
"$name"Read a variable (always quote it)
$(command)Capture a command's output
if [ ... ]; then ... fiConditional
for x in ...; do ... doneLoop over items
while [ ... ]; do ... doneLoop while true
name() { ... }Define a function
$1 $@ $# $?Args, all args, count, last exit code
cmd1 && cmd2Run cmd2 only if cmd1 succeeds
cmd > file 2>&1Redirect output + errors to a file

Troubleshooting

SymptomLikely cause & fix
Permission denied on runNot executable — chmod +x script.sh.
command not found: ./script.shRun with ./ from its folder, or bash script.sh.
Variable empty unexpectedlyTypo, or you wrote name = value with spaces. Remove the spaces.
Breaks on filenames with spacesQuote every variable: "$file".
Script keeps going after an errorAdd set -euo pipefail at the top.
Unsure why it failsRun bash -x script.sh to trace each line.

Your Challenge

  • Add a check: if the user passes no argument and the default folder is missing, print usage and exit.
  • After backup, delete archives older than 7 days (hint: find "$backup_dir" -name '*.tar.gz' -mtime +7 -delete).
  • Add a --help flag that prints how to use the script.
  • Bonus: count how many backups exist and print the total size of the backup folder.
if [ "${1:-}" = "--help" ]; then echo "Usage: ./backup.sh [folder-to-back-up]" exit 0 fi

Recap & What's Next

You can now

Write executable Bash scripts with variables, conditionals, loops, arguments, and functions — and you built a real backup tool. This is the automation mindset DevOps runs on.

Next up: Module 4 — Git & GitHub, where you'll track changes to code (including your scripts) and collaborate — and create the repo you'll use for the rest of the course.

Bash Scripting

Objectives Why Bash Building Blocks Hands-on Lab Full Script Cheat Sheet Troubleshooting Challenge Recap