Bash Scripting
A pentest produces mountains of text: subdomains, ports, URLs, users. The difference between losing an afternoon copying and pasting and solving it in thirty seconds is a Bash loop. And when you land on a victim with no tools, the shell is often all you have: knowing how to sweep hosts or ports with what’s already installed is survival. This page goes from a variable to a robust script.
Concepts
Section titled “Concepts”Variables and quoting
Section titled “Variables and quoting”target="10.10.10.5" # no spaces around =echo "Scanning $target" # double quotes: expand variablesecho 'Literal: $target' # single quotes: expand nothingports=(22 80 443) # arrayecho "${ports[1]}" # 80 (indices start at 0)echo "${#ports[@]}" # 3 elements| Expansion | Result |
|---|---|
$(command) |
The command’s output (command substitution) |
$((3 + 4)) |
Integer arithmetic |
${var:-default} |
The value of var, or default if it’s empty |
${file%.txt} · ${path##*/} |
Strip a suffix · keep just the file name |
Arguments and exit codes
Section titled “Arguments and exit codes”| Variable | Contents |
|---|---|
$0 |
The script’s name |
$1, $2… |
Positional arguments |
$# |
Number of arguments |
"$@" |
All arguments, each quoted separately |
$? |
Exit code of the last command (0 = success) |
$$ |
The script’s own PID |
A script ends with exit 0 if everything went well and another number if not. That way it chains with && and || like any other command.
Conditions
Section titled “Conditions”if [[ -f "$file" && -r "$file" ]]; then echo "Exists and is readable"elif [[ -z "$file" ]]; then echo "You didn't give me a file" >&2 exit 1fi| Test | True if… |
|---|---|
-f f · -d d · -e x |
It’s a file · a directory · exists |
-r · -w · -x |
Readable · writable · executable |
-z "$v" · -n "$v" |
Empty · not empty |
"$a" == "$b" · != |
Strings equal · different (== accepts patterns: == *.php) |
$a -eq $b · -lt · -gt |
Numeric comparison |
"$v" =~ ^[0-9]+$ |
Matches the regular expression |
[[ ... ]] is the bash version (safer and more capable); [ ... ] is the POSIX one, the only one you’ll have if the script runs under sh.
case "$port" in 80|8080) echo "HTTP" ;; 443) echo "HTTPS" ;; *) echo "Other" ;;esac# Over a sequencefor i in {1..254}; do echo "10.10.10.$i"; done
# Over a file's lines: while read is the robust waywhile IFS= read -r url; do code=$(curl -s -o /dev/null -w '%{http_code}' "$url") echo "$code $url"done < urls.txtfor line in $(cat file) looks equivalent but splits on spaces, not lines: use while IFS= read -r.
Functions
Section titled “Functions”alive() { ping -c1 -W1 "$1" &>/dev/null # returns ping's exit code}
if alive 10.10.10.5; then echo "responds"; fiVariables inside a function are global unless you declare them local.
Robust scripts
Section titled “Robust scripts”#!/usr/bin/env bashset -euo pipefail # stop on the first error, undefined variables and pipeline failures
[[ $# -eq 1 ]] || { echo "Usage: $0 <hosts_file>" >&2; exit 1; }hosts="$1"out="results_$(date +%Y%m%d_%H%M)"mkdir -p "$out"trap 'echo "Interrupted" >&2' INT # what to do if someone hits Ctrl+C| Option | Effect |
|---|---|
set -e |
Exit as soon as a command fails |
set -u |
Using an undefined variable is an error (catches typos) |
set -o pipefail |
A pipeline fails if any part of it fails, not just the last one |
set -x |
Print each command before running it: for debugging |
In practice
Section titled “In practice”# Host sweep without nmap (in parallel with &, and wait for all)for i in {1..254}; do (ping -c1 -W1 "10.10.10.$i" &>/dev/null && echo "10.10.10.$i alive") &done; wait# TCP port scan with no tools, using /dev/tcp (bash only, not sh)host=10.10.10.5for p in 21 22 80 139 443 445 3306 8080; do (timeout 1 bash -c "echo > /dev/tcp/$host/$p") 2>/dev/null && echo "$p open"done# Pull IPs with open ports out of nmap's grepable outputgrep '/open/' scan.gnmap | awk '{print $2}' | sort -u > alive.txt
# Which web servers repeat in a list of headersgrep -i '^server:' headers.txt | sort | uniq -c | sort -rn
# Check a list of URLs and keep those answering 200while IFS= read -r u; do [[ $(curl -s -o /dev/null -w '%{http_code}' "$u") == 200 ]] && echo "$u"done < urls.txtNext offensive step
Section titled “Next offensive step”- When Bash falls short (complex parsing, HTTP requests, exploits): Python.
- To extract exactly the data you’re after: regular expressions.
- The same on Windows: PowerShell.
Cheat sheet
Section titled “Cheat sheet”| Concept | What to remember |
|---|---|
var=value |
No spaces. "$var" always quoted. |
"..." · '...' |
Expands · literal. |
$(cmd) · $((a+b)) |
A command’s output · arithmetic. |
$1 · $# · "$@" · $? |
Argument · count · all · exit code. |
[[ -f f ]] · -z · -eq |
File exists · empty · numeric equality. |
while IFS= read -r |
The right way to read a file line by line. |
local |
Variables that don’t leak out of the function. |
set -euo pipefail |
At the top of every serious script. |
& + wait |
Parallelise and wait. |
/dev/tcp/host/port |
TCP connections without tools (bash only). |
ShellCheck · bash -n |
Review · syntax check. |
Review questions
Section titled “Review questions”-
What’s the difference between
echo "$HOME"andecho '$HOME'?Answer
The first prints the variable’s value (your home folder); the second prints
$HOMEliterally, because single quotes expand nothing. -
Why can
for l in $(cat urls.txt)give wrong results?Answer
Because command substitution splits on spaces, tabs and newlines, and also expands wildcards. A line with spaces becomes several iterations.
while IFS= read -r l; do …; done < urls.txtreads line by line without altering the content. -
What does
set -euo pipefaildo and why is it worth it?Answer
-estops the script at the first failing command,-utreats undefined variables as errors, andpipefailmakes a pipeline fail if any of its commands fails. It keeps the script from carrying on with empty or wrong data. -
How do you check whether port 445 on a machine is open without nmap or nc?
Answer
With bash:
timeout 1 bash -c "echo > /dev/tcp/IP/445" && echo open. If the connection is established, the command succeeds. -
Your script works with
bash script.shbut fails withsh script.sh. What do you suspect?Answer
That it uses bash-only features (
[[ ]], arrays,{1..10},/dev/tcp) andshis dash, which lacks them. Fix it with a#!/usr/bin/env bashshebang and run it with bash, or rewrite it in POSIX. -
What does a Bash function return if it has no
return?Answer
The exit code of the last command it ran. That’s why a function ending in
pingcan be used directly in anif.