Learn / Stage 2: Linux / Lesson 2.3

$ lesson 2.3 --stage linux --scripts

Bash Scripting for Security

Typing commands is where you start; scripts are how defenders keep up. Learn variables, quoting, conditions, loops and functions by running real security scripts in your browser, then automate backups and log checks on your VM, and learn to spot a dangerous script before it runs.

  • Stage 2 Linux
  • Level Beginner to intermediate
  • 60 min
  • 6 sections, quiz, lab

Start the lesson Jump to the lab

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
2.3.01

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.

How a script runs: you run the file, the kernel reads the shebang, bash runs the lines, and the script ends with an exit code./backup.shyou run it#!/bin/bashkernel reads shebangbashruns line by lineexit 0or 1 to 255needs execute permission (chmod +x), or run it as: bash backup.sh$? holds the exit code: 0 means success
Running ./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/bash tells the kernel which interpreter to use. #!/usr/bin/env bash finds bash on the PATH instead, which is handy on systems where it lives elsewhere.
  • set -e stops the script when a command fails, -u treats an unset variable as an error instead of silently using an empty string, and -o pipefail makes a pipeline fail if any command in it fails, not just the last one. They catch a lot of mistakes, though -e has exceptions (commands inside if conditions, for example), so still check the results that matter.
2.3.02

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, $2 and so on, $# is how many there are, "$@" is all of them, and $0 is 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.

2.3.03

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:

Common bash tests
TestTrue 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.

A pipeline: grep finds failed logins, a second grep pulls out the IP, cut, sort and uniq count them, and sort -rn ranks themgrepFailed passwordgrep -oEfrom [0-9.]+cutfield 2sortuniq -csort-rneach tool does one small job; | joins them into an answer
The heart of 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.
2.3.04

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.

student@cwm-lab: Bash scripting sandbox

Missions 0/8

    Simulated in your browser. Nothing runs on a real machine.

    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.

    2.3.05

    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 +%F gives 2026-11-24, so files sort by date and never overwrite each other.
    • The .sha256 file lets you prove later that the backup was not changed: sha256sum -c etc-2026-11-24.tar.gz.sha256 prints OK or FAILED.
    • find ... -mtime +7 -delete removes copies older than seven days. Test it first with -print instead 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.sh

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

    2.3.06

    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:

    1. Download, do not pipe: curl -fsSLo install.sh URL.
    2. Verify it when the publisher gives a checksum or signature: sha256sum install.sh and compare every character, or verify the GPG signature.
    3. 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.
    4. Lint and dry run: bash -n for syntax, ShellCheck for bugs, bash -x to trace each command as it runs, inside a snapshot of your lab VM first.
    5. Run with the least privilege it needs. Most scripts do not need sudo for every line.
    Script red flags
    Red flagWhy it matters
    curl ... | bash or wget -O- ... | shRuns unseen remote code
    echo ... | base64 -d | bashHides what will run
    Writes to ~/.ssh/authorized_keysGives someone passwordless access
    Adds cron jobs or .service filesSurvives reboots: persistence
    chmod 777 or chmod u+sOpens files to everyone or creates a SUID root binary
    rm -rf "$VAR/" without checksOne 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?

    Q2A script runs rm -rf "$TMPDIR/"* and TMPDIR is unset. What happens?

    Q3grep -q admin /etc/passwd; echo $? prints 1. What does that mean?

    Q4Which loop reads ips.txt one line at a time?

    Q5Root's cron runs /opt/clean.sh, and the file is world writable. The risk?

    Q6Safest way to use an install script from a website?

    0 / 6

    Hands-on lab

    lab45 minutesyour own machines only

    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.

    1. 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.log

      Fix anything ShellCheck reports. If your VM has no failures yet, create some from your PC as in lesson 2.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.sha256

      The check must print OK. Then change one byte of the archive copy in /tmp and see it fail.

    3. Schedule it

      $ sudo crontab -e
      30 2 * * * /usr/local/sbin/backup_etc.sh >> /var/log/backup_etc.log 2>&1
      $ sudo crontab -l

      For a quick test use */2 * * * *, wait two minutes, check the log, then set it back.

    4. 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 FILE and 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.

    5. Audit a real install script

      Download (do not pipe) an install script from a project you know, for example curl -fsSLo install.sh followed 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.

    Download the lab checklist (.txt)

    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.