By the end of this lesson you can
- Write scripts with a shebang, strict mode, variables, arguments and exit codes
- Use if, for, while read and functions to process logs and files
- Quote variables correctly and explain what goes wrong when you do not
- Schedule a backup with checksums using cron
- Audit someone else's script for red flags before running it
Why defenders script
A script is a text file of shell commands that bash runs from top to bottom. That sounds small, but it is how security work scales. Checking one server's logins by hand takes five minutes. Checking fifty servers every morning is only possible if a script does it while you drink your tea.
Typical defensive scripts are short and boring, which is exactly what you want: count failed logins per IP, back up configs and record their checksums, list new SUID files since yesterday, check that every server has the latest updates, collect evidence from a machine you suspect. Each one is a pipeline you already know from lesson 2.2, wrapped in variables, conditions and loops.
./backup.sh: the kernel reads the first line (the shebang) to choose the interpreter, bash runs the lines in order, and the script finishes with an exit code that callers can check.Two lines start almost every good script:
#!/bin/bash
set -euo pipefail- The shebang
#!/bin/bashtells the kernel which interpreter to use.#!/usr/bin/env bashfinds bash on the PATH instead, which is handy on systems where it lives elsewhere. set -estops the script when a command fails,-utreats an unset variable as an error instead of silently using an empty string, and-o pipefailmakes a pipeline fail if any command in it fails, not just the last one. They catch a lot of mistakes, though-ehas exceptions (commands insideifconditions, for example), so still check the results that matter.
Variables, quoting, arguments and exit codes
Variables hold text. There are no spaces around =, and you read a variable with $:
$ target=/var/log/auth.log
$ echo "Checking $target"
Checking /var/log/auth.log
$ count=$(grep -c 'Failed password' "$target")
$ echo "$count failures, $((count * 2)) if it doubles"$(command)runs a command and captures what it prints.$((...))does whole number arithmetic.- Scripts get their arguments as
$1,$2and so on,$#is how many there are,"$@"is all of them, and$0is the script's own name. ${1:-/var/log/auth.log}means: use the first argument, or this default if it is missing.
Quote your variables
This is the rule that prevents the most damage. Without quotes, bash splits a variable's value on spaces and expands any * in it. A file called my report.txt becomes two arguments, and a value of * becomes every file in the folder. Write "$file", not $file, unless you know exactly why you want splitting. Single quotes are fully literal: '$HOME' prints the five characters $HOME.
Exit codes
Every command returns a number when it finishes, stored in $?. 0 means success; anything from 1 to 255 means some kind of failure. grep returns 1 when nothing matched, 127 means command not found, 126 means found but not executable. && runs the next command only on success and || only on failure, so grep -q root /etc/passwd && echo found is a tiny if statement. In your own scripts, end with exit 0 on success and exit 1 (or another non zero code) with a message on stderr (echo "error" >&2) when something is wrong, so cron, CI pipelines and other scripts can tell.
Conditions, loops and functions
#!/bin/bash
set -euo pipefail
# if: test a condition
if [ "$(id -u)" -ne 0 ]; then
echo "run me with sudo" >&2
exit 1
fi
# for: repeat for each item
for f in /etc/passwd /etc/shadow /etc/sudoers; do
ls -l "$f"
done
# while read: process a file line by line
while read -r user _ ; do
echo "checking $user"
done < users.txt
# function: name a block you reuse
log() { echo "$(date +%F' '%T) $*" >> /var/log/mycheck.log; }
log "permissions checked"The [ ] test (also written test) is how bash asks questions. The common ones:
| Test | True when |
|---|---|
[ -f path ] | path exists and is a regular file |
[ -d path ] | path is a directory |
[ -r path ] | you can read it (-w write, -x execute) |
[ -z "$v" ] | the string is empty (-n: not empty) |
[ "$a" = "$b" ] | strings are equal (!= not equal) |
[ "$n" -gt 5 ] | numbers: -eq -ne -lt -le -gt -ge |
Bash also has [[ ]], a safer built in version that handles empty variables better and adds pattern matching like [[ $file == *.log ]]. Use it in bash scripts; use [ ] when a script must also run under plain sh.
while read -r line is the standard way to walk through a file or a command's output. The -r stops backslashes being treated as escapes, which matters when you read log lines. With two or more names (read -r count ip) it splits each line on spaces and the last name gets the rest of the line.
failed_logins.sh: five small tools joined by pipes. The script adds an argument for the log file, a minimum count and a check that the file is readable.Practice: run, check and fix scripts in the browser
The practice shell below understands variables, $(...), $((...)), if, for, while read, functions and exit codes, so the scripts in ~/scripts really run. It is simplified (no editor, no real network), but every habit carries over to your VM.
Missions 0/8
Try more on your own: echo $((6 * 7)), for i in 1 2 3; do echo "round $i"; done, n=$(wc -l < /etc/passwd); echo "$n accounts", or while read -r u role; do echo "$u is $role"; done < users.txt.
Real automation: backups, checksums and cron
Here is a backup script a defender might actually schedule. Read it slowly; every line is a habit.
#!/bin/bash
# backup_etc.sh: archive /etc, record its checksum, keep 7 days
set -euo pipefail
dest="${BACKUP_DIR:-/var/backups/etc}"
stamp=$(date +%F)
file="$dest/etc-$stamp.tar.gz"
mkdir -p "$dest"
tar -czf "$file" /etc 2>/dev/null
sha256sum "$file" > "$file.sha256"
find "$dest" -name 'etc-*.tar.gz*' -mtime +7 -delete
echo "backup ok: $file"date +%Fgives2026-11-24, so files sort by date and never overwrite each other.- The
.sha256file lets you prove later that the backup was not changed:sha256sum -c etc-2026-11-24.tar.gz.sha256printsOKorFAILED. find ... -mtime +7 -deleteremoves copies older than seven days. Test it first with-printinstead of-delete: a dry run.
Scheduling with cron
Cron runs commands on a schedule. Edit your table with crontab -e (or root's with sudo crontab -e). Each line has five time fields, then the command:
# minute hour day-of-month month day-of-week command
30 2 * * * /usr/local/sbin/backup_etc.sh >> /var/log/backup_etc.log 2>&1
*/15 * * * * /usr/local/sbin/check_logins.shThe first line runs at 02:30 every day and appends all output to a log; the second runs every 15 minutes. Cron runs with a very small environment, so use full paths to scripts and files. Systemd timers (systemctl list-timers) are the modern alternative with better logging, and lesson 2.4 shows how attackers abuse both.
Reading other people's scripts safely
Tutorials love one liners like curl -fsSL https://example.com/install.sh | sudo bash. It is convenient and sometimes fine from a vendor you trust, but understand what it means: you run whatever that server sends at that moment, as root, without seeing it. A compromised website, a typo in the domain, or a malicious forum post turns it into malware installation.
A safer routine for any script you did not write:
- Download, do not pipe:
curl -fsSLo install.sh URL. - Verify it when the publisher gives a checksum or signature:
sha256sum install.shand compare every character, or verify the GPG signature. - Read it. Look for further downloads (
curl,wget), encoded blobs (base64 -d), changes to~/.ssh, cron, systemd or sudoers, and anything sent to a remote IP. - Lint and dry run:
bash -nfor syntax, ShellCheck for bugs,bash -xto trace each command as it runs, inside a snapshot of your lab VM first. - Run with the least privilege it needs. Most scripts do not need sudo for every line.
| Red flag | Why it matters |
|---|---|
curl ... | bash or wget -O- ... | sh | Runs unseen remote code |
echo ... | base64 -d | bash | Hides what will run |
Writes to ~/.ssh/authorized_keys | Gives someone passwordless access |
Adds cron jobs or .service files | Survives reboots: persistence |
chmod 777 or chmod u+s | Opens files to everyone or creates a SUID root binary |
rm -rf "$VAR/" without checks | One empty variable deletes everything |
Flashcards: do you remember?
Tap a card to flip it. Try to answer in your head first; recalling is what makes it stick.
Quick quiz
Instant feedback on every answer. Score 70% or more to pass this lesson's quiz.
Q1What prints Hello Madhav if name=Madhav?
Double quotes expand variables; single quotes keep the text literal.
Q2A script runs rm -rf "$TMPDIR/"* and TMPDIR is unset. What happens?
An empty variable turns it into rm -rf /*. Use set -u and ${TMPDIR:?}.
Q3grep -q admin /etc/passwd; echo $? prints 1. What does that mean?
grep returns 0 when it finds a match and 1 when it finds none (2 for errors).
Q4Which loop reads ips.txt one line at a time?
for over the literal name would loop once over the word ips.txt.
Q5Root's cron runs /opt/clean.sh, and the file is world writable. The risk?
Writable root scripts are a classic privilege escalation.
Q6Safest way to use an install script from a website?
Piping runs unseen code as root.
Hands-on lab
Lab: automate three security checks on your VM
You need: Your Ubuntu lab VM from lesson 2.2 (take a snapshot first) and sudo apt install -y shellcheck.
Only on machines you own. Do this lab on your own VM or computer. Scanning, testing or accessing anyone else's system without written permission can be an offence under the Information Technology Act, 2000 (for example Sections 43 and 66).
Write the failed login counter
$ mkdir -p ~/scripts && nano ~/scripts/failed_logins.sh # type the script from the practice section $ chmod u+x ~/scripts/failed_logins.sh $ shellcheck ~/scripts/failed_logins.sh $ sudo ~/scripts/failed_logins.sh /var/log/auth.logFix anything ShellCheck reports. If your VM has no failures yet, create some from your PC as in lesson 2.2.
Write and test the backup script
$ sudo nano /usr/local/sbin/backup_etc.sh $ sudo chown root:root /usr/local/sbin/backup_etc.sh && sudo chmod 700 /usr/local/sbin/backup_etc.sh $ sudo /usr/local/sbin/backup_etc.sh $ ls -l /var/backups/etc $ cd /var/backups/etc && sudo sha256sum -c etc-*.tar.gz.sha256The check must print
OK. Then change one byte of the archive copy in /tmp and see it fail.Schedule it
$ sudo crontab -e 30 2 * * * /usr/local/sbin/backup_etc.sh >> /var/log/backup_etc.log 2>&1 $ sudo crontab -lFor a quick test use
*/2 * * * *, wait two minutes, check the log, then set it back.Write a SUID watcher
$ sudo find / -perm -4000 -type f 2>/dev/null | sort > ~/suid-baseline.txt $ nano ~/scripts/suid_diff.sh # compare a fresh list with the baseline using: diff ~/suid-baseline.txt <(sudo find / -perm -4000 -type f 2>/dev/null | sort)Make it print
NEW SUID FILEand exit 1 when the lists differ, and exit 0 when they match. Test it by creating a SUID copy in your home folder, then delete that copy.Audit a real install script
Download (do not pipe) an install script from a project you know, for example
curl -fsSLo install.shfollowed by the URL from its official docs. Read it and list every download, file it writes and command it runs as root. Do not run it.
You are done when: ShellCheck reports nothing on your scripts, the backup runs from cron and its checksum verifies, and the SUID watcher catches the test file.
Key takeaways
- Start scripts with a shebang and set -euo pipefail.
- Quote every variable and guard rm with ${VAR:?}.
- Exit codes and && / || are how scripts make decisions.
- Cron and timers automate checks, but root's scripts must be writable only by root.
- Read, verify and lint any script before you run it, never pipe unknown code into a shell.
Finished the sections, quiz and lab? Mark the lesson complete. Progress is saved only in this browser.