Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Practice library / Linux

Workbook · Easy · 3 hours

Bash Scripting

Shell scripting, conditionals, loops, and automation on Linux.

  • bash
  • shell-scripting
  • automation
  • linux
On this page 4 sections
  1. ·About This Workbook
  2. ·Chapter 1 — Script Basics
  3. ·Chapter 2 — Logic & Loops
  4. ·Chapter 3 — Text & Automation

Before you start

Shell scripting on Linux ties together the small commands that make up every security workflow. Bash is the default shell on nearly every target machine and nearly every attack platform. This workbook covers the parts you need in real work: safe quoting, argument handling with positional parameters and getopts, branching with [[ ]] and case, and loops that process files, hosts and command output without corrupting the data. You will also use grep, awk, cut, sort, uniq and jq to turn tool output into evidence. The focus stays on the pattern of enumeration, filtering and action that repeats across triage, log work and fleet checks.

New to Linux? This workbook assumes you can already move around a Linux filesystem and run commands. If you cannot yet, start with Linux for Beginners, then come back.

What You'll Learn

  • Write a script that fails loudly instead of silently — and know exactly where set -euo pipefail stops protecting you
  • Quote correctly, and recognise the word-splitting bugs that quoting prevents
  • Take arguments safely, with positional parameters and with getopts
  • Branch with [[ ]], (( )) and case, and loop over files, hosts and command output without corrupting the data
  • Cut findings out of tool output with grep, awk, cut, sort, uniq and jq
  • Build a repeatable check that cleans up after itself and exits with a status another script can act on

About This Workbook

Bash is not an elegant language, but it is installed on nearly every machine where a security professional gets a shell. Every tool on that machine works with it by default. It is also the shortest path from "I ran three commands by hand and found something" to "this check now runs against four hundred hosts every morning."

That combination is why security work is so shell-shaped. Enumeration, log triage, evidence collection, checking a control across a fleet — these are all take output, filter it, decide something, do it again problems, which is precisely what Bash is for.

This workbook assumes you can already move around a Linux filesystem and run commands. It teaches you to turn those commands into scripts other people can trust: scripts that fail loudly, that survive a filename with a space in it, and that exit with a status a pipeline can read.

Two practical notes before you start.

Bash is not one thing. Features arrive in versions, and the version you get depends on the machine. Everything in this workbook was checked against Bash 3.2, so it will also work on 4.x and 5.x. Where something needs a newer shell, it is called out. Check the installed version before you debug an unexplained failure:

bash --version
GNU bash, version 3.2.57(1)-release (arm64-apple-darwin25)

That is the shell Apple still ships as /bin/bash on macOS. Most current Linux distributions ship 5.x. mapfile/readarray and associative arrays (declare -A) both need 4.0 or newer, and on 3.2 declare -A fails outright:

bash: declare: -A: invalid option

Authorisation. Several examples here probe hosts and read logs. Scanning, probing or connecting to systems you do not own requires written authorisation with a defined scope and time window before you run anything. Automation makes an out-of-scope mistake fast and repeated. Run the network examples against your own lab hosts.

Chapter 1 — Script Basics

From one-liners to real scripts.

Shebang and execution

A script is a text file whose first line tells the kernel which interpreter to hand it to. That line is the shebang, and it must be the very first bytes of the file.

bashtriage.sh
#!/usr/bin/env bash
# triage.sh — first-look collection on a host you have been given.
set -euo pipefail

printf '== host ==\n'
hostname
printf '\n== who is logged in ==\n'
who
printf '\n== listening sockets ==\n'
ss -tulpn 2>/dev/null || netstat -tulpn 2>/dev/null || printf 'no ss or netstat\n'

Two choices in that first line are worth defending. #!/usr/bin/env bash looks up bash on PATH, so it finds the 5.x Bash a user installed under /usr/local/bin rather than an older system one; #!/bin/bash hardcodes a path that is right on most Linux systems and wrong on some others. The trade-off is that env makes the script depend on the caller's PATH. Pick one deliberately. Do not try to pass options on the shebang line (#!/usr/bin/env bash -e) — behaviour varies between systems. Put set -e in the body where it is visible anyway.

Make it executable and run it:

chmod +x triage.sh
./triage.sh

./triage.sh runs the file through the interpreter named in the shebang. bash triage.sh ignores the shebang entirely and uses whatever bash you invoked — useful for testing, misleading if you forget you did it. sh triage.sh is worse: on Debian and Ubuntu /bin/sh is dash, not Bash, and every Bash-only feature in this workbook will break in ways that look like typos.

The safety line

set -euo pipefail is the most valuable line in the file. Each part does a specific job.

  • -e (errexit) — exit when a command fails, instead of ploughing on with bad state.
  • -u (nounset) — treat an unset variable as an error. This catches typos, and it stops the classic rm -rf "$PREFIX/" disaster where PREFIX was never set.
  • -o pipefail — a pipeline's exit status becomes that of the rightmost command that failed, not just the last command's.

That last one changes real outcomes:

false | true; echo "without pipefail: $?"
set -o pipefail; false | true; echo "with pipefail:    $?"
without pipefail: 0
with pipefail:    1

set -e is not a safety net, it is a tripwire — and it has holes. It deliberately does not fire for a command in an if or while condition, for a command negated with !, or for any command in an &&/|| chain other than the last. So false && true will not stop your script.

The most common problem is the last line of a function. A function whose final statement is [[ -f "$f" ]] && do_thing returns 1 when the file is absent, because that is the status of the && list. Under set -e the caller then dies, silently, on a line that looks like a no-op. Use a real if block when the test is the last thing a function does, or end the function with an explicit return 0.

Variables

Assignment takes no spaces around the =. Expansion needs $, and — with vanishingly few exceptions — needs double quotes around it.

target="10.10.5.20"
outdir="/tmp/scan results"          # a path with a space, as in real life
readonly RATE_LIMIT=5               # readonly: reassignment is an error
stamp="$(date -u +%Y%m%dT%H%M%SZ)"  # command substitution

printf 'writing %s to %s at %s\n' "$target" "$outdir" "$stamp"

Use $( ) for command substitution, never backticks: it nests, and it does not change quoting rules halfway through. Lowercase names for your own variables and uppercase for exported environment variables is a convention, not a rule, but following it stops you shadowing something like PATH by accident.

Quoting is a leading source of Bash bugs, and the failure is worth seeing once:

f="report final.txt"
rm $f      # WRONG — the shell splits this into two arguments
rm "$f"    # right
rm: report: No such file or directory
rm: final.txt: No such file or directory

Unquoted, the shell splits the value on whitespace and then expands any * or ? as a glob. Quoted, the value is one argument. An attacker who controls a filename controls your unquoted expansion, which is how a filename becomes command injection.

Parameter expansion gives you defaults and required-value checks without an if:

port="${PORT:-443}"                    # use 443 if PORT is unset or empty
outdir="${OUTDIR:?set OUTDIR first}"   # abort with this message if unset or empty
name="${1##*/}"                        # strip everything up to the last slash
base="${name%.txt}"                    # strip a trailing .txt

Arguments

Inside a script, $1, $2, … are the positional parameters, $# is how many there are, $0 is the script's own name, and $? is the exit status of the last command. Two of these are easy to confuse, and the difference matters:

show() { echo "argument count: $#"; }
set -- "two words" second
show "$@"    # each parameter stays one argument
show "$*"    # all parameters joined into a single argument
argument count: 2
argument count: 1

Use "$@" — quoted, always — whenever you pass a script's arguments on to something else. "$*" is for building a display string, and nothing else.

For anything with more than one or two inputs, use the getopts builtin rather than hand-rolling a parser. It handles clustered short options and -t value, and it is in every POSIX shell. It does not do GNU-style long options such as --target; if you need those, use a different language.

bashsweep.sh
#!/usr/bin/env bash
# sweep.sh — usage: ./sweep.sh -t targets.txt [-p 443] [-v]
set -euo pipefail

targets=""; port=443; verbose=0

while getopts ":t:p:v" opt; do
  case "$opt" in
    t) targets="$OPTARG" ;;
    p) port="$OPTARG" ;;
    v) verbose=1 ;;
    :)  printf 'option -%s needs a value\n' "$OPTARG" >&2; exit 2 ;;
    \?) printf 'unknown option -%s\n'      "$OPTARG" >&2; exit 2 ;;
  esac
done
shift $((OPTIND - 1))

: "${targets:?-t targets.txt is required}"
printf 'targets=%s port=%s verbose=%s extra-args=%s\n' \
  "$targets" "$port" "$verbose" "$#"

The leading colon in ":t:p:v" switches getopts into silent error mode so your own messages appear instead of the shell's. A colon after a letter means that option takes a value, delivered in $OPTARG. shift $((OPTIND - 1)) discards the options it consumed, leaving any remaining operands as $1 onward.

./sweep.sh -t targets.txt -p 8443 -v
./sweep.sh -p 8443
./sweep.sh -z
targets=targets.txt port=8443 verbose=1 extra-args=0
./sweep.sh: line 18: targets: -t targets.txt is required
unknown option -z

Note the exit statuses those produce: 0, 1, 2. Distinct codes for "fine", "you gave me bad input" and "I could not run" are what let a wrapper script or a CI job react correctly. Send diagnostics to stderr with >&2 so that redirecting stdout to a results file does not swallow your errors.

Chapter 2 — Logic & Loops

Making scripts make decisions.

Conditionals

Bash gives you three test constructs and they are not interchangeable.

[[ ... ]] is the Bash keyword for string and file tests. It does not word-split or glob its operands, it supports &&, || and =~ for regex, and it is the preferred choice in Bash. [ ... ] is the older POSIX command — portable to dash, but it needs every operand quoted. (( ... )) is arithmetic: use it for numbers.

f="/etc/shadow"

if [[ -r "$f" ]]; then
  echo "readable: $f"
elif [[ -e "$f" ]]; then
  echo "exists but not readable by $(id -un): $f"
else
  echo "absent: $f"
fi

failures=7
if (( failures > 5 )); then
  echo "threshold exceeded"
fi

ip="203.0.113.45"
if [[ $ip =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
  echo "looks like an IPv4 address"
fi

The file tests you will use constantly are -e (exists), -f (regular file), -d (directory), -r/-w/-x (readable, writable, executable by this process), and -s (exists and is non-empty). For strings, -z is empty and -n is non-empty. For integers inside [[ ]] you need -eq, -ne, -lt, -le, -gt, -ge — < and > inside [[ ]] compare strings, so [[ 10 > 9 ]] is false. Inside (( )) the ordinary < and > work as arithmetic, which is a good reason to use (( )) for numbers.

That regex check is deliberately labelled "looks like": it matches 999.999.999.999 too. Validating the shape of input is cheap and worth doing; validating the value needs a real parser.

When you are branching on one value against several patterns, case reads better than a chain of elif:

case "$severity" in
  critical|high) printf 'page on-call\n' ;;
  medium)        printf 'raise a ticket\n' ;;
  low|info)      printf 'log only\n' ;;
  *)             printf 'unknown severity: %s\n' "$severity" >&2; exit 2 ;;
esac

The *) arm is not optional. Without it, an unexpected value falls straight through and your script treats "I have no idea what this is" as "nothing to do".

Loops

for iterates over a list. Quote the array expansion or you are back to word splitting:

hosts=("10.10.5.20" "10.10.5.31" "10.10.5.44")

for h in "${hosts[@]}"; do
  printf 'queued %s\n' "$h"
done
printf 'array length: %s\n' "${#hosts[@]}"

for ((i = 1; i <= 3; i++)); do
  printf 'attempt %d\n' "$i"
done

To iterate over files, use a glob directly — for f in ./*.pcap — never for f in $(ls). Command substitution on ls splits on whitespace and breaks on the first filename containing a space.

To read a file line by line, use this form:

while IFS= read -r line; do
  printf 'got: [%s]\n' "$line"
done < hosts.txt

IFS= prevents leading and trailing whitespace being trimmed. -r stops read from interpreting backslashes as escapes. Both options default to behaviour that is wrong for this task, so the line can seem unnecessary until a hostname with a trailing space is silently changed.

The subshell trap. Bash runs each stage of a pipeline in a subshell, so a while loop on the right-hand side of a pipe cannot change variables in the parent shell. Counters reset, arrays come back empty, and nothing warns you. Feed the loop by redirection or process substitution instead of by pipe.

The following script shows the effect. The first counter is always zero; the second is correct:

n=0
printf 'a\nb\nc\n' | while IFS= read -r l; do n=$((n + 1)); done
echo "after pipe: n=$n"

n=0
while IFS= read -r l; do n=$((n + 1)); done < <(printf 'a\nb\nc\n')
echo "after process substitution: n=$n"
after pipe: n=0
after process substitution: n=3

Note the space in < <( — that is a redirection followed by a process substitution, and it is a Bash feature, not POSIX.

Functions

Functions keep a script readable and testable. Declare locals with local, or every variable is global and loops can overwrite each other's counters.

#!/usr/bin/env bash
set -euo pipefail

log() {
  printf '[%s] %s\n' "$(date -u +%H:%M:%SZ)" "$*" >&2
}

port_open() {
  local host="$1" port="$2"
  timeout 3 bash -c "cat < /dev/null > /dev/tcp/$host/$port" 2>/dev/null
}

log "probing"
if port_open scanme.lab.local 443; then
  echo "443 open"
else
  echo "443 closed or filtered"
fi

A function's "return value" is its exit status: 0 for success, non-zero for failure, and it must fit in 0–255. That is why port_open is written to be used directly in an if — it returns whatever timeout returned. If you want to hand back data rather than a verdict, print it to stdout and capture it with result="$(myfunc)".

/dev/tcp/host/port is not a real device file; it is a redirection Bash implements itself. It is a handy dependency-free reachability check, but some distributions compile Bash with network redirections disabled, so test it in your environment before relying on it. timeout comes from GNU coreutils and is not present everywhere either.

Finally, make cleanup automatic rather than remembered. trap runs a command when the shell exits — including when it exits because set -e killed it:

workdir="$(mktemp -d)"
trap 'rm -rf "$workdir"' EXIT

mktemp -d creates a directory with a name nobody can predict and permissions only you can read, which is the point: writing intermediate scan output to a fixed /tmp/scan creates a local privilege-escalation risk.

Chapter 3 — Text & Automation

Wrangling output into useful results.

Pipes and filters

Security tools emit text. Your job is to reduce that text to the handful of lines that mean something. Each tool in the pipeline does one narrow thing:

  • grep selects lines. -E for extended regex, -o to print only the matching part, -i to ignore case, -v to invert, -c to count, -r to recurse, -h to suppress filename prefixes.
  • cut -d: -f1,3 slices fixed-delimiter fields. awk does the same job when the delimiter is whitespace or the logic is conditional.
  • sort orders; sort -u deduplicates; sort -rn sorts numerically, descending.
  • uniq -c counts adjacent duplicates — it only works on sorted input, which is why sort | uniq -c is one idiom rather than two commands.
  • tr, head, tail, wc -l handle the small stuff.

The following pipeline is one of the most common in security work. It identifies who is brute-forcing SSH:

grep 'Failed password' /var/log/auth.log \
  | awk '{ for (i = 1; i <= NF; i++) if ($i == "from") print $(i+1) }' \
  | sort | uniq -c | sort -rn | head
  47 203.0.113.45
  12 198.51.100.9
   3 192.0.2.77

That awk walks the fields looking for the literal word from and prints the field after it, rather than hardcoding $11. Field positions in syslog move when a hostname changes length or the daemon changes its message; the anchor word does not.

Where that log lives is environment-dependent. Debian and Ubuntu write SSH authentication events to /var/log/auth.log; RHEL-family systems use /var/log/secure. On a systemd host with no syslog daemon installed, the events may exist only in the journal, and you would start from journalctl -u ssh (Debian family) or journalctl -u sshd (RHEL family) instead. Check before you assume.

Parsing output

awk earns its keep when you need a condition as well as a field. Listing interactive local accounts:

awk -F: '$3 >= 1000 && $7 !~ /(nologin|false)$/ { print $1, $3, $7 }' /etc/passwd
deploy 1000 /bin/bash
svc-backup 1001 /bin/bash

-F: sets the field separator, $3 is the UID and $7 the shell. The 1000 threshold is the common modern convention, not a standard — older RHEL systems started regular users at 500, and the authoritative value on any given host is UID_MIN in /etc/login.defs. Also note that /etc/passwd is only the local file; getent passwd returns accounts from every configured NSS source, including LDAP, and on a domain-joined host that difference can be the key finding.

The same shape works on tool output. Nmap's greppable format puts one host per line, and each open port appears as a port/state/protocol/... record:

nmap -sn 10.10.5.0/24 -oG - | awk '/Status: Up/ { print $2 }' > live-hosts.txt
nmap -iL live-hosts.txt -oG scan.gnmap
grep -oE '[0-9]+/open/tcp' scan.gnmap | cut -d/ -f1 | sort -un
22
80
443
8080

Extracting with grep -oE '[0-9]+/open/tcp' rather than counting slash-separated fields is a deliberate choice: it does not care how many empty fields the record has. Still, greppable output is a convenience format. When a parse has to survive an Nmap upgrade, take XML with -oX and feed it to a real XML parser.

Modern tooling increasingly speaks JSON, and jq is the right tool for JSON, not grep:

jq -r '.findings[] | select(.severity == "high") | "\(.host):\(.port)"' findings.json
10.10.5.20:8080

-r prints raw strings instead of quoted JSON. Regexes over JSON break on whitespace and escaping; jq does not. It is a separate package on most distributions, but it is a stable, long-lived one and worth installing on any box you work from regularly.

Automation patterns

Four patterns turn a working pipeline into something you can schedule.

Run the slow parts in parallel. Network checks spend nearly all their time waiting, so run them concurrently with xargs -P:

xargs -P 8 -I{} sh -c \
  'code=$(curl -s -o /dev/null -w "%{http_code}" --max-time 8 "https://{}/"); \
   printf "%s %s\n" "$code" "{}"' < hosts.txt | sort -k2

Timings depend entirely on the network, but the difference can be large: in one test run, three HTTPS checks took about 6.8 seconds serially and about 0.7 seconds with -P 8. Two cautions. Interleaved output from parallel jobs can tear mid-line, so have each job print one short line and sort afterwards. And -P is a rate multiplier pointed at someone else's infrastructure — keep it low unless your authorisation says otherwise.

Handle awkward filenames. find and xargs agree on a NUL separator, which is the only byte that cannot appear in a filename:

find /var/www -type f -name '*.bak' -print0 | xargs -0 -n1 sha256sum
find / -perm -4000 -type f 2>/dev/null | sort

The second is the classic SUID sweep. 2>/dev/null discards the permission-denied noise from directories you cannot read — useful here, but be aware you are also discarding real errors.

Check your dependencies before you need them, so the script fails on line 5 with a clear message rather than on line 200 half way through writing a report:

for tool in nmap jq openssl; do
  if ! command -v "$tool" >/dev/null 2>&1; then
    printf 'required tool not found: %s\n' "$tool" >&2
    exit 3
  fi
done

Exit with a status that means something. Here is all of it in one script: a TLS certificate expiry check you can put on a schedule.

bashcert-expiry.sh
#!/usr/bin/env bash
# cert-expiry.sh — report TLS certificates expiring inside a window.
# Usage: ./cert-expiry.sh hosts.txt [days]
# Exit 0 = every host healthy. Exit 1 = at least one host needs attention.
set -euo pipefail

hostfile="${1:?usage: $0 hosts.txt [days]}"
days="${2:-30}"
window=$(( days * 86400 ))

workdir="$(mktemp -d)"
trap 'rm -rf "$workdir"' EXIT

check_host() {
  local host="$1"
  local pem="$workdir/$host.pem"

  if ! timeout 10 openssl s_client -connect "$host:443" -servername "$host" \
        </dev/null 2>/dev/null > "$pem"; then
    printf 'UNREACHABLE  %s\n' "$host"
    return 1
  fi

  if openssl x509 -in "$pem" -noout -checkend "$window" >/dev/null 2>&1; then
    printf 'OK           %s  (%s)\n' "$host" "$(openssl x509 -in "$pem" -noout -enddate)"
    return 0
  fi

  printf 'EXPIRING     %s  (%s)\n' "$host" "$(openssl x509 -in "$pem" -noout -enddate)"
  return 1
}

rc=0
while IFS= read -r host; do
  case "$host" in ''|'#'*) continue ;; esac
  check_host "$host" || rc=1
done < "$hostfile"

exit "$rc"
./cert-expiry.sh hosts.txt 30
echo "exit=$?"
OK           example.com  (notAfter=Oct 27 22:17:21 2026 GMT)
OK           www.iana.org  (notAfter=Sep 28 21:37:55 2026 GMT)
UNREACHABLE  no-such-host.invalid
exit=1

Everything from the first two chapters is doing a job in there. ${1:?…} makes the argument mandatory with a usable message. ${2:-30} gives a sane default. mktemp -d plus trap … EXIT means no temporary file outlives the run, even on a crash. case skips blanks and # comments so the host list can be documented. check_host "$host" || rc=1 records a failure without letting set -e abandon the remaining hosts — the || is load-bearing.

The expiry test is openssl x509 -checkend <seconds>, which exits 0 if the certificate will still be valid that far ahead and 1 if it will not. Using it avoids date arithmetic entirely, which matters because GNU date -d and BSD date -j -f take completely different arguments and a script that parses dates by hand may work on only one platform.

Before you commit it

Two commands and a habit catch many of the remaining errors.

bash -n cert-expiry.sh     # parse only: syntax errors, nothing executed
shellcheck cert-expiry.sh  # static analysis: quoting, portability, dead code
bash -x cert-expiry.sh hosts.txt   # trace every expanded command as it runs

ShellCheck is a high-value tool. It reads your script and tells you the specific thing that is wrong:

In bad.sh line 3:
rm $f
   ^-- SC2086 (info): Double quote to prevent globbing and word splitting.

In bad.sh line 4:
for i in `ls`; do echo $i; done
         ^--^ SC2045 (error): Iterating over ls output is fragile. Use globs.
         ^--^ SC2006 (style): Use $(...) notation instead of legacy backticks `...`.

Every one of those is a bug this workbook warned you about, found automatically. Run it before anything of yours goes into a repository or a cron job.

bash -x prints each command after expansion, prefixed with +, which makes it quick to see why a command behaved as it did:

+ host=web01
+ echo 'checking web01'
checking web01

You can switch it on for one section with set -x and off again with set +x, which is far more usable than tracing a whole script.

Two habits that keep scripts out of incident reports. Never put a credential in a script or pass one as a command-line argument — arguments are visible to every user on the box via ps. Read secrets from a file with restrictive permissions or from the environment. And when a value comes from outside the script — a filename, a hostname from a list, a field parsed out of a log — never interpolate it into eval or into a string you hand to another shell. Validate its shape first, quote it always.

Keep going. Work through each chapter in order, then apply what you learned in the matching labs. An effective way to consolidate this is to take a check you currently do by hand, write it as a script that exits 0 or 1, and run shellcheck over it until it is silent.

Sign in to track progress and send feedback.

Related

This workbook is extra practice for the course Linux. Do the lessons first.Open the course