Bash Scripting
Bash is the pentester’s glue on Linux: it automates repetitive tasks (run the same tool against 100 hosts), chains one tool’s results into another, and processes massive output down to just the useful datum. You don’t need to be a programmer; you need to know how to turn “do this for each line of this file” into a three-line script.
Script basics
Section titled “Script basics”#!/bin/bash # shebang: which interpreter runs itname="theoffsecgirl" # variable (no spaces around =)echo "Hi $name" # variable expansion$(command) # command substitution -> captures outputchmod +x script.sh && ./script.sh # make executable and runVariables, arguments, and conditionals
Section titled “Variables, arguments, and conditionals”$1 $2 ... # positional arguments$# # number of arguments$0 # script name$? # exit code of the last command (0 = success)
if [ "$1" = "go" ]; then echo "go"; else echo "no"; fi[ -f file ] # does the file exist? [ -z "$x" ] empty?Loops (the heart of automation)
Section titled “Loops (the heart of automation)”# iterate over a file's lines (hosts, users, URLs)while read host; do echo "[*] scanning $host" nmap -p80,443 "$host"done < hosts.txt
# iterate over a range or listfor ip in 192.168.1.{1..254}; do ping -c1 -W1 "$ip" &>/dev/null && echo "$ip up"; doneProcessing text (pipes + utilities)
Section titled “Processing text (pipes + utilities)”80% of the value is here: turning output into information.
cat urls.txt | grep admin # filter linescut -d: -f1 /etc/passwd # column 1 by delimiter ':'awk '{print $1}' access.log # field 1 (by spaces)sort | uniq -c | sort -rn # count and sort by frequencytr ',' '\n' # replace characterssed 's/http/https/g' file # find and replaceReal example — most frequent IPs in a log:
awk '{print $1}' access.log | sort | uniq -c | sort -rn | headUseful pentest one-liners
Section titled “Useful pentest one-liners”# extract all URLs from a filegrep -oE 'https?://[^ "]+' file.txt | sort -u# simple port sweep without nmapfor p in 22 80 443 445; do (echo >/dev/tcp/10.0.0.1/$p) &>/dev/null && echo "$p open"; doneWhy it matters in security
Section titled “Why it matters in security”Almost no tool does exactly what you need; Bash fills the gaps: parse one tool’s output and feed another, automate an attack over a list, clean wordlists, or build a homemade scan. In the Offensive Python course you’ll see many tasks start in Bash before justifying a Python script.
Mastery checklist
Section titled “Mastery checklist”- I write a script with a shebang and variables and make it executable
- I use arguments ($1, $#) and conditionals ([ … ])
- I iterate over a file with while read and over a range with for
- I filter and transform text with grep/cut/awk/sed/sort/uniq
- I compose pipe one-liners to extract data from output
- I capture output with $(…) and check $?
- I automate a tool over a target list