Skip to content
Pwnversity
FUND-BASHbasic · 10 min · upd. 2026-11

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.

Ventana de terminal
target="10.10.10.5" # no spaces around =
echo "Scanning $target" # double quotes: expand variables
echo 'Literal: $target' # single quotes: expand nothing
ports=(22 80 443) # array
echo "${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
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.

Ventana de terminal
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 1
fi
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.

Ventana de terminal
case "$port" in
80|8080) echo "HTTP" ;;
443) echo "HTTPS" ;;
*) echo "Other" ;;
esac
Ventana de terminal
# Over a sequence
for i in {1..254}; do echo "10.10.10.$i"; done
# Over a file's lines: while read is the robust way
while IFS= read -r url; do
code=$(curl -s -o /dev/null -w '%{http_code}' "$url")
echo "$code $url"
done < urls.txt

for line in $(cat file) looks equivalent but splits on spaces, not lines: use while IFS= read -r.

Ventana de terminal
alive() {
ping -c1 -W1 "$1" &>/dev/null # returns ping's exit code
}
if alive 10.10.10.5; then echo "responds"; fi

Variables inside a function are global unless you declare them local.

#!/usr/bin/env bash
set -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
Ventana de terminal
# 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
Ventana de terminal
# TCP port scan with no tools, using /dev/tcp (bash only, not sh)
host=10.10.10.5
for 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
Ventana de terminal
# Pull IPs with open ports out of nmap's grepable output
grep '/open/' scan.gnmap | awk '{print $2}' | sort -u > alive.txt
# Which web servers repeat in a list of headers
grep -i '^server:' headers.txt | sort | uniq -c | sort -rn
# Check a list of URLs and keep those answering 200
while IFS= read -r u; do
[[ $(curl -s -o /dev/null -w '%{http_code}' "$u") == 200 ]] && echo "$u"
done < urls.txt
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.
  1. What’s the difference between echo "$HOME" and echo '$HOME'?

    Answer

    The first prints the variable’s value (your home folder); the second prints $HOME literally, because single quotes expand nothing.

  2. 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.txt reads line by line without altering the content.

  3. What does set -euo pipefail do and why is it worth it?

    Answer

    -e stops the script at the first failing command, -u treats undefined variables as errors, and pipefail makes a pipeline fail if any of its commands fails. It keeps the script from carrying on with empty or wrong data.

  4. 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.

  5. Your script works with bash script.sh but fails with sh script.sh. What do you suspect?

    Answer

    That it uses bash-only features ([[ ]], arrays, {1..10}, /dev/tcp) and sh is dash, which lacks them. Fix it with a #!/usr/bin/env bash shebang and run it with bash, or rewrite it in POSIX.

  6. 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 ping can be used directly in an if.