Bash Scripting
Automate the Boring Parts

person 0x74shelby category Fundamentals · Beginner
screenshot_monitor

01

Variables and Input

Shell scripting is how you stop repeating yourself. Anything you type more than twice should probably be a script. For security work this means: automating host discovery, processing wordlists, parsing tool output, and running the same recon steps against multiple targets without the manual overhead.

Variables in bash are set without spaces around the equals sign. They're accessed with a dollar sign. Command substitution wraps a command in $() and uses its output as a value. $1, $2, etc. are positional parameters — arguments passed to the script.

bash variables
#!/bin/bash
TARGET=$1
PORT=${2:-80}
DATE=$(date +%Y%m%d)

echo "Scanning $TARGET on port $PORT"
echo "Started: $DATE"
02

Conditionals and Loops

If statements in bash check exit codes. A command that succeeds returns 0 (true). Failure returns non-zero. The test command (or [ ]) checks conditions: -f tests if a file exists, -z tests for empty string, -eq compares integers. For loops iterate over lists. While loops run until a condition changes.

loops and conditionals
for ip in $(seq 1 254); do
  ping -c 1 -W 1 192.168.1.$ip &>/dev/null && \
    echo "192.168.1.$ip is up"
done

while IFS= read -r subdomain; do
  result=$(host "$subdomain.target.com" 2>/dev/null)
  [[ "$result" == *"has address"* ]] && echo "$subdomain.target.com found"
done < subdomains.txt
03

Security Automation Examples

A recon script that runs against a target, collects all open ports, and then automatically runs targeted scripts against each one saves hours on every engagement. The key is making it idempotent — running it twice shouldn't break anything — and making it output structured, parseable results rather than just terminal output.

recon script skeleton
#!/bin/bash
TARGET=$1
OUTDIR="recon_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$OUTDIR"

echo "[*] All ports scan..."
nmap -sS -p- --min-rate 5000 "$TARGET" -oN "$OUTDIR/allports.txt"

PORTS=$(grep "^[0-9]" "$OUTDIR/allports.txt" | cut -d'/' -f1 | tr '\n' ',' | sed 's/,$//')

echo "[*] Targeted scan on: $PORTS"
nmap -sV -sC -p "$PORTS" "$TARGET" -oN "$OUTDIR/targeted.txt"
echo "[+] Done. Results in $OUTDIR/"

Pipes and Redirection

The real power of bash is chaining tools with pipes. cat file | grep pattern | awk '{print $2}' | sort -u filters, extracts, and deduplicates in one line. Learning to compose tool output this way is what separates people who use security tools from people who write efficient security workflows.