Skip to content

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.

#!/bin/bash # shebang: which interpreter runs it
name="theoffsecgirl" # variable (no spaces around =)
echo "Hi $name" # variable expansion
$(command) # command substitution -> captures output
chmod +x script.sh && ./script.sh # make executable and run
$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?
# 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 list
for ip in 192.168.1.{1..254}; do ping -c1 -W1 "$ip" &>/dev/null && echo "$ip up"; done

80% of the value is here: turning output into information.

cat urls.txt | grep admin # filter lines
cut -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 frequency
tr ',' '\n' # replace characters
sed 's/http/https/g' file # find and replace

Real example — most frequent IPs in a log:

awk '{print $1}' access.log | sort | uniq -c | sort -rn | head
# extract all URLs from a file
grep -oE 'https?://[^ "]+' file.txt | sort -u
# simple port sweep without nmap
for p in 22 80 443 445; do (echo >/dev/tcp/10.0.0.1/$p) &>/dev/null && echo "$p open"; done

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.

  • 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