RBCloud & DevOpsTHE PRACTICAL LEARNING LIBRARY
By Ravindra BagaleResources

CHAPTER 12 / 60

Bash scripting and repeatable administration

Write a parameterized script that validates its inputs and fails visibly.

Concept + practical labBy Ravindra Bagale · ~5 min read · lab time additional

Shell fundamentals

Variables use name=value with no spaces around =. Reference with "$name" to prevent word splitting. $? is the preceding exit status, $1 the first positional argument and $# the argument count. $(command) captures stdout. Arrays preserve separate arguments more safely than concatenated command strings.

A practical backup script

Save as backup-lab.sh; it copies only a selected directory into a timestamped archive.

bash
#!/usr/bin/env bash
set -euo pipefail
src=${1:?Usage: backup-lab.sh SOURCE DESTINATION}
dest=${2:?Usage: backup-lab.sh SOURCE DESTINATION}
[[ -d "$src" ]] || { echo 'Source must be a directory' >&2; exit 1; }
mkdir -p "$dest"
src=$(realpath "$src")
dest=$(realpath "$dest")
case "$dest/" in "$src/"*) echo 'Destination must be outside source' >&2; exit 1;; esac
stamp=$(date -u +%Y%m%dT%H%M%SZ)
out="$dest/backup-$stamp-$$.tar.gz"
tar -czf "$out" -C "$src" .
tar -tzf "$out" >/dev/null
printf 'Created %s\n' "$out"
bash
chmod 750 backup-lab.sh
./backup-lab.sh ~/academy/notes ~/academy/backup
bash -n backup-lab.sh

set -e has contextual exceptions; it is not a universal error handler. pipefail makes a failed pipeline stage visible. Quoted variables preserve paths with spaces. A destination outside the source prevents the archive from including itself.

Conditions and loops

bash
for service in nginx sshd; do
  if systemctl is-active --quiet "$service"; then
    printf '%s is running\n' "$service"
  else
    printf '%s is not active or not installed\n' "$service"
  fi
done

Ubuntu commonly names the SSH service ssh, so adapt the list. Use functions for repeated logic and traps for temporary-file cleanup. Do not store passwords directly in scripts or enable set -x around secrets.

Verification and assignment

Run the backup with a valid directory, with a missing source and with a destination inside the source. Restore the successful archive into a new directory and compare files. Add a retention policy only after implementing a dry-run listing of exactly which archives would be removed.

Official reference

Bash reference manual

Ravindra’s Tip

Script को सही input से ही नहीं, गलत input से भी test करो। Automation में छोटी गलती बार-बार और तेजी से दोहरती है।

Interview and revision check

Why quote variable expansions used as paths?

Quotes prevent word splitting and wildcard expansion from turning one intended path into multiple unexpected arguments.

Ravindra Bagale · Cloud & DevOps Academy · Handbook and project downloads