DEV Community

Muhammad Khizr Khan
Muhammad Khizr Khan

Posted on AI-assisted

DevOps from Zero #2: Bash Scripting, your first automation

I'm Muhammad Khizr Khan, a computer science student and full-stack/DevOps developer, learning DevOps in public one class at a time. In Class 01 we typed Linux commands one by one. Today we put them in a file and let the computer do the work: our first real automation.

The rule I'm following: if you type it twice, script it.

What a Bash script is

A plain text file of commands that Bash runs from top to bottom. Scripts are repeatable (same steps every time), fast, and shareable: the whole team runs exactly the same thing.

Anatomy of a script, and how to run it

#!/bin/bash              # shebang: run this with Bash (must be line 1)
# a comment              # ignored by Bash
echo "Hello, DevOps!"    # commands, top to bottom
Enter fullscreen mode Exit fullscreen mode

Run it:

chmod +x hello.sh   # once: make it runnable
./hello.sh          # ./ means "the file in this folder"
Enter fullscreen mode Exit fullscreen mode

Variables

name="Khizr"             # NO spaces around =
echo "Hi $name"          # double quotes fill in the value
echo 'Hi $name'          # single quotes print it literally
today=$(date +%F)        # save a command's output
echo "${name}-$today"    # braces separate the name from text
Enter fullscreen mode Exit fullscreen mode

The classic beginner bug: name = "Khizr" (with spaces) fails. name="Khizr" works.

Arguments and input: one script, many jobs

Syntax Meaning
$0 The script's own name
$1, $2 … First, second argument: ./deploy.sh staging v2.1
$# How many arguments were given
${1:-default} Use $1, or a default if it's empty
read -p "Q? " v Ask the user and store the answer in v

Conditions: scripts that make decisions

if [ -f "config.txt" ]; then
    echo "found"
elif [ -d "config" ]; then
    echo "it's a folder"
else
    echo "missing"
fi
Enter fullscreen mode Exit fullscreen mode
Test Meaning
-f / -d Is a file / is a folder
-z "$x" Text is empty
-eq -ne -gt -lt Numbers: equal, not equal, greater, less
"$a" = "$b" Text is the same
! Not: [ ! -d "$dir" ]

⚠️ Spaces matter: [ -f "x" ] works, [-f "x"] fails. And always quote your variables: "$file".

Loops: do it to 1,000 files, write it once

for file in *.log; do         # each item in a list
    gzip "$file"
done

count=1
while [ $count -le 3 ]; do    # while the test is true
    echo "Attempt $count"
    count=$((count + 1))      # maths goes inside $(( ))
done
Enter fullscreen mode Exit fullscreen mode

Exit codes: how every command says "it worked"

  • Every command returns a number, stored in $?. 0 = success, 1–255 = failure.
  • a && b runs b only if a worked. a || b runs b only if a failed.
  • exit 1 ends your script with a failure code, so other tools (like CI pipelines) know it failed.
  • Put set -euo pipefail at the top of serious scripts: stop at the first error, treat unset variables as errors, and catch failures inside pipes.

Functions

log() {
    echo "[$(date +%T)] $1"     # $1 = the function's own argument
}
log "Starting checks"           # call it like a command
Enter fullscreen mode Exit fullscreen mode

Use local for variables that should only live inside the function.

Two real-world scripts

  • backup.sh: checks that the folder exists, packs it with tar -czf into a dated file, then deletes backups older than 7 days with find … -mtime +7 -delete.
  • health.sh: asks a website for its status code with curl -s -o /dev/null -w "%{http_code}" and appends UP or DOWN to a log with >>.

Scheduling with cron: let the server work while you sleep

Run crontab -e and add one line per job: minute hour day month weekday command.

*/5 * * * *  ~/health.sh     # every 5 minutes
0 2 * * *    ~/backup.sh     # every night at 2:00
0 9 * * 1    ~/report.sh     # every Monday at 9:00
Enter fullscreen mode Exit fullscreen mode

🧪 Lab (30 minutes)

  1. greet.sh: print Hello, NAME using $1
  2. Usage check: if [ -z "$1" ], print how to use the script and exit 1
  3. count.sh: for f in *.txt, run wc -l "$f"
  4. backup.sh: back up ~/devops/class-01
  5. Bonus: schedule it daily with crontab -e

Next class

Networking: how the internet actually reaches your server.


I'm Muhammad Khizr Khan, a full-stack & DevOps developer and the founder of Axelink Systems. More of my work is on my portfolio, LinkedIn and GitHub. Did the lab? Post your first script in the comments and I'll review it.

Top comments (0)