01 · INTRODUCTION

🎯 What Is Bash Scripting?

Bash (Bourne Again SHell) is a command-line interpreter and scripting language that comes pre-installed on virtually every Linux and macOS system. It was created by Brian Fox in 1989 as a free replacement for the original Bourne shell (sh). Today, Bash is the default shell on most Linux distributions — including Kali Linux, Parrot OS, and Ubuntu — making it the lingua franca of the Linux command line.

A Bash script is simply a text file containing a sequence of commands that the shell executes in order. But Bash is far more than a command runner — it's a full programming language with variables, loops, conditionals, functions, arrays, and even basic arithmetic. This makes it incredibly powerful for automation.

For ethical hackers and penetration testers, Bash is not optional — it's essential. Almost every tool you'll use (Nmap, Metasploit, Gobuster, Nikto, Hydra, Netcat) is either written in Bash, called from Bash, or best orchestrated through Bash. Mastering Bash means you can chain tools together, automate repetitive tasks, and build custom tooling — skills that separate a script kiddie from a professional.

02 · WHY BASH FOR HACKERS

💡 Why Ethical Hackers Love Bash

You might wonder: "Why not just use Python for everything?" Great question. Python is fantastic, but Bash has unique advantages in the security world:

🐧

Pre-installed Everywhere

Every Linux box has Bash. No installation, no dependencies, no setup — just open a terminal and go.

⚡

Native System Access

Direct access to /dev/tcp, /proc, netstat, ps, and every system tool — no wrappers needed.

🔗

Perfect Glue Language

Chain Nmap → Grep → Awk → Curl in one line. Bash is the duct tape of the security toolkit.

🚀

Instant Prototyping

Write a working recon script in 30 seconds. No compiler, no virtual environment, no boilerplate.

🕵️

Stealth & Evasion

Bash scripts often bypass AV detection better than compiled binaries — they're just text files.

📜

Universal Skill

Every sysadmin, DevOps engineer, and security pro knows Bash. It's the common language.

💡 Pro Insight: The best hackers don't choose between Bash and Python — they combine them. Use Bash for system orchestration and quick tasks; use Python for complex logic and parsing. Together, they're unstoppable.
03 · FUNDAMENTALS

📚 Bash Fundamentals

Every Bash script starts with a shebang — a special first line that tells the operating system which interpreter to use. Without it, the system doesn't know your script is Bash.

#!/bin/bash # This is a comment. It's ignored by the shell. echo "Hello, ethical hacker!"

Making a Script Executable

After writing your script, you need to give it execute permissions:

chmod +x myscript.sh ./myscript.sh

The Anatomy of a Bash Command

Every command follows this pattern: command [options] [arguments]

ls -la /var/log # ls = command, -la = options, /var/log = argument

Essential Commands Every Hacker Must Know

CommandPurposeExample
lsList directory contentsls -la
cdChange directorycd /etc
pwdPrint working directorypwd
catView file contentscat /etc/passwd
grepSearch text patternsgrep "root" /etc/passwd
findSearch for filesfind / -name "*.conf"
chmodChange file permissionschmod 755 script.sh
psList running processesps aux
netstatShow network connectionsnetstat -tuln
curlTransfer data over HTTPcurl -I https://target.com
04 · VARIABLES & DATA

📦 Variables, Arrays & User Input

Variables store data that you can reuse throughout your script. In Bash, you assign a value with = (no spaces around it!) and access it with $.

# Variable assignment (NO spaces around =) target="192.168.1.100" port=22 username="admin" # Accessing variables (use $ prefix) echo "Scanning $target on port $port" # Best practice: always quote your variables echo "User: $username"

Special Variables

Arrays

Bash supports both indexed and associative arrays. Indexed arrays are perfect for wordlists, IP ranges, and port lists.

# Indexed array ports=(21 22 80 443 3306 8080) # Access an element echo "First port: ${ports[0]}" # Loop through all elements for p in "${ports[@]}"; do echo "Checking port $p" done # Array length echo "Total ports: ${#ports[@]}"

Reading User Input

read -p "Enter target IP: " target read -sp "Enter password: " password echo "Target: $target"
🔑 Key Rule: Always wrap your variables in double quotes: "$var". This prevents word splitting and glob expansion — two of the most common sources of Bash bugs.
05 · CONTROL FLOW

🔀 Conditionals, Loops & Logic

Control flow is what makes scripts intelligent. Instead of running commands blindly, your script can make decisions and repeat actions.

If / Elif / Else

if [ "$USER" = "root" ]; then echo "[+] Running as root — full access" elif [ "$USER" = "admin" ]; then echo "[!] Running as admin — limited access" else echo "[-] Running as $USER — restricted" fi

Comparison Operators

OperatorMeaningType
-eqEqual toNumeric
-neNot equal toNumeric
-gtGreater thanNumeric
-ltLess thanNumeric
== or =Equal toString
!=Not equalString
-zString is emptyString
-nString is not emptyString
-fFile existsFile test
-dDirectory existsFile test
-xFile is executableFile test

For Loops

Perfect for iterating over lists, files, IP ranges, or wordlist entries.

# Loop over a range for i in {1..10}; do echo "Attempt $i" done # Loop over a file line by line while IFS= read -r line; do echo "Processing: $line" done < targets.txt # C-style for loop for ((i=1; i<=254; i++)); do ping -c 1 -W 1 "192.168.1.$i" &>/dev/null && echo "Live: 192.168.1.$i" done

While & Until Loops

# While loop — runs as long as condition is TRUE count=0 while [ $count -lt 5 ]; do echo "Count: $count" ((count++)) done # Until loop — runs UNTIL condition becomes TRUE until [ -f "/tmp/flag" ]; do sleep 1 done

Case Statement

Cleaner than multiple if/elif when matching many values.

case "$1" in scan) echo "Running scan..." ;; exploit) echo "Running exploit..." ;; report) echo "Generating report..." ;; *) echo "Usage: $0 {scan|exploit|report}" ;; esac
06 · FUNCTIONS

🧩 Functions — Modular Scripting

Functions let you package reusable blocks of code. They make scripts shorter, cleaner, and easier to debug.

# Define a function scan_port() { host="$1" port="$2" timeout 1 bash -c "echo >/dev/tcp/$host/$port" 2>/dev/null if [ $? -eq 0 ]; then echo "[+] $host:$port OPEN" fi } # Call the function scan_port "192.168.1.1" 22 scan_port "192.168.1.1" 80 # Return values with echo (Bash functions return exit codes, not values) get_ip() { echo "192.168.1.50" } my_ip=$(get_ip) echo "Target: $my_ip"
📌 Remember: Bash functions can only return exit codes (0–255) via return. To return actual data, use echo and capture it with $(function_name).
07 · PIPES & REDIRECTION

🔗 Pipes, Redirection & Streams

Pipes and redirection are what make Bash so powerful. They let you connect commands together like Lego bricks — the output of one becomes the input of another.

The Three Streams

Pipe Operator |

Send the output of one command directly into another:

# Find all IPs in a log file and count unique ones cat access.log | grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | sort -u | wc -l # Check for open SSH port via Nmap output nmap -p 22 192.168.1.1 | grep "open"

Redirection Operators

OperatorMeaning
>Redirect stdout to a file (overwrite)
>>Redirect stdout to a file (append)
<Redirect file as stdin
2>Redirect stderr to a file
2>&1Redirect stderr to same place as stdout
&>Redirect both stdout and stderr
>/dev/nullDiscard output (silence)
# Save scan results to a file, suppress errors nmap -sV 192.168.1.1 > scan.txt 2>/dev/null # Append results echo "[+] Scan complete at $(date)" >> scan.txt # Silence both output streams ping -c 1 192.168.1.1 &>/dev/null
08 · TEXT PROCESSING

✂️ Text Processing — The Hacker's Scalpel

90% of a pentester's job involves parsing text: extracting IPs from logs, filtering Nmap output, and pulling URLs from web pages. Master these three tools and you'll never struggle again.

grep — Search & Filter

# Basic search grep "error" /var/log/syslog # Case-insensitive grep -i "failed" auth.log # Recursive search grep -r "password" /var/www/ # Invert match (show lines NOT containing pattern) grep -v "#" config.conf # Extended regex — extract IPs grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' access.log

awk — Column Extraction

# Print first column of a file awk '{print $1}' users.txt # Print last column awk '{print $NF}' data.txt # Filter by condition awk '$3 > 1000 {print $1, $3}' traffic.log # Custom delimiter (CSV) awk -F',' '{print $2}' users.csv

sed — Stream Editing

# Replace text sed 's/old/new/g' file.txt # Delete lines matching a pattern sed '/^#/d' config.conf # Print only specific lines (5 to 10) sed -n '5,10p' file.txt # In-place edit (careful!) sed -i 's/localhost/127.0.0.1/g' config.ini

Other Must-Know Text Tools

🔪 cut — Extract fields
🔢 sort — Sort lines
📊 uniq — Remove duplicates
🔢 wc — Count lines/words
🔤 tr — Translate characters
📏 head/tail — First/last lines
🔗 paste — Merge files
🌐 jq — Parse JSON
09 · ESSENTIAL TOOLS

🔧 Tools Every Bash Hacker Uses

Bash scripts become truly powerful when they orchestrate these security tools. Here's what you'll use daily:

🌐 Nmap — Port scanning
💥 Metasploit — Exploitation
🔍 Gobuster — Directory brute-force
🕷️ Nikto — Web scanner
🔐 Hydra — Login brute-force
📡 Netcat — Network swiss army knife
🦈 Wireshark — Packet analysis
🔎 Dig / nslookup — DNS recon
📥 Curl / Wget — HTTP requests
🛡️ OpenSSL — Crypto toolkit
🔬 tcpdump — Packet capture
📦 sqlmap — SQL injection

Example: Chaining Nmap + Grep + Awk

# Extract all open ports from an Nmap scan nmap -p- -T4 192.168.1.1 -oG - | grep "open" | awk '{print $1, $2}' # Find live hosts on a /24 subnet for i in {1..254}; do ping -c 1 -W 1 "192.168.1.$i" >/dev/null 2>&1 && echo "192.168.1.$i UP" & done wait
10 · REAL SCRIPTS

⚙️ Real-World Hacking Scripts

Script 1: Multi-Threaded Ping Sweeper

Quickly discover live hosts on a subnet using parallel background jobs.

#!/bin/bash # Ping sweep an entire /24 subnet subnet="${1:-192.168.1}" echo "[*] Sweeping $subnet.0/24..." for i in {1..254}; do ( ping -c 1 -W 1 "$subnet.$i" >/dev/null 2>&1 && \ echo "[+] $subnet.$i is ALIVE" ) & done wait echo "[✓] Sweep complete."

Script 2: Simple Port Scanner

Uses Bash's built-in /dev/tcp — no external tools needed.

#!/bin/bash # Port scanner using /dev/tcp target="$1" ports=(21 22 23 25 53 80 110 143 443 445 3306 3389 8080) if [ -z "$target" ]; then echo "Usage: $0 <target-ip>" exit 1 fi echo "[*] Scanning $target..." for port in "${ports[@]}"; do timeout 1 bash -c "echo >/dev/tcp/$target/$port" 2>/dev/null if [ $? -eq 0 ]; then echo " [+] Port $port OPEN" fi done echo "[✓] Done."

Script 3: Web Directory Brute-Forcer

Lightweight Gobuster alternative using curl.

#!/bin/bash # Simple web directory brute-forcer url="$1" wordlist="$2" if [ ! -f "$wordlist" ]; then echo "Wordlist not found: $wordlist" exit 1 fi while IFS= read -r dir; do code=$(curl -s -o /dev/null -w "%{http_code}" "$url/$dir") if [ "$code" != "404" ]; then echo "[+] $url/$dir → $code" fi done < "$wordlist"

Script 4: Log Monitoring for Suspicious Logins

Blue-team style monitoring of SSH authentication logs.

#!/bin/bash # Watch for failed SSH logins logfile="/var/log/auth.log" echo "[*] Monitoring $logfile for failed logins..." tail -Fn0 "$logfile" | while read -r line; do if echo "$line" | grep -q "Failed password"; then ip=$(echo "$line" | grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}') echo "[!] Brute-force attempt from: $ip" fi done
11 · USE CASES

🎯 Where Bash Shines in Ethical Hacking

🔎

Recon Automation

Loop through subdomains, run dig and whois, and log results automatically.

🌐

Network Sweeping

Ping sweep an entire subnet and identify live hosts in seconds with parallel jobs.

🔧

Tool Wrapping

Wrap nmap, gobuster, or hydra into repeatable workflows.

📊

Log Parsing

Extract IPs, errors, and patterns from massive log files with grep + awk.

🛡️

Blue Team Defense

Monitor auth logs and alert on suspicious SSH login attempts in real time.

🚀

Payload Delivery

Automate file transfers, reverse shells, and post-exploitation cleanup.

📁

Report Generation

Collect scan results and format them into clean reports automatically.

12 · BEST PRACTICES

✅ Best Practices for Clean, Safe Scripts

  1. Always quote variables — Use "$var" to prevent word splitting and glob expansion.
  2. Use set -euo pipefail — Fail fast on errors, undefined variables, and pipe failures.
  3. Comment generously — Future you (and teammates) will thank you.
  4. Validate all input — Never trust user-supplied arguments; sanitize before use.
  5. Log everything — Redirect output to timestamped files for audit trails.
  6. Use functions — Keep scripts modular; avoid one giant block of code.
  7. Handle errors explicitly — Check exit codes with $? and act on failures.
  8. Test in a lab — Use VirtualBox, VMware, or Docker before running on real targets.
  9. Use mktemp for temp files — Avoid predictable filenames in /tmp.
  10. Never hardcode credentials — Use environment variables or config files with restricted permissions.

The Magic Line: set -euo pipefail

#!/bin/bash set -euo pipefail # -e : Exit immediately if a command fails # -u : Treat unset variables as errors # -o pipefail : Catch failures in piped commands
💡 Pro Tip: Add set -x temporarily when debugging. It prints every command before executing it, making it easy to spot where things go wrong.
13 · ERROR HANDLING

🛠️ Robust Error Handling

Professional scripts don't crash silently. They detect problems, log them, and either recover or exit cleanly.

Check Exit Codes

nmap -sV 192.168.1.1 -oN scan.txt if [ $? -ne 0 ]; then echo "[!] Nmap failed. Check target and permissions." >&2 exit 1 fi echo "[+] Scan completed successfully."

Trap Signals

Clean up on exit — even if the user presses Ctrl+C.

cleanup() { echo "[*] Cleaning up temporary files..." rm -f "/tmp/scan_$$.tmp" } trap cleanup EXIT INT TERM tmpfile="/tmp/scan_$$.tmp" nmap -sV 192.168.1.1 > "$tmpfile"

Custom Error Function

error() { echo "[ERROR] $1" >&2 exit 1 } [ $# -lt 1 ] && error "Usage: $0 <target>" [ ! -f "$1" ] && error "File not found: $1"
14 · ADVANCED

🚀 Advanced Topics

Arithmetic in Bash

a=10 b=3 echo $((a + b)) # 13 echo $((a - b)) # 7 echo $((a * b)) # 30 echo $((a / b)) # 3 echo $((a % b)) # 1 echo $((a ** b)) # 1000 # Increment ((a++)) echo "$a" # 11

Process Substitution

Treat command output as a file — powerful for diffing and comparisons.

# Compare output of two commands diff <(nmap 192.168.1.1) <(nmap 192.168.1.2) # Feed multiple inputs to a single command cat <(echo "host1") <(echo "host2") > hosts.txt

Background Jobs & Parallelism

# Run tasks in parallel and wait for all to finish for ip in 192.168.1.{1..10}; do (nmap -T4 -p 22,80,443 "$ip" > "scan_$ip.txt") & done wait echo "[+] All scans finished."

Here Documents (Heredoc)

cat <<EOF > payload.sh #!/bin/bash echo "Hello from payload" EOF chmod +x payload.sh

Reading Files Safely

# Preserve whitespace and backslashes with IFS= and -r while IFS= read -r line; do echo "Line: $line" done < targets.txt

String Manipulation

str="https://example.com/path" echo ${str#https://} # example.com/path (remove prefix) echo ${str%.com*} # https://example (remove suffix) echo ${str/https/http} # http://example.com/path (replace) echo ${#str} # string length echo ${str^^} # HTTPS://EXAMPLE.COM/PATH echo ${str,,} # lowercase
16 · CONCLUSION

🎓 Final Thoughts

Bash scripting is the backbone of Linux-based ethical hacking. It's the skill that transforms you from someone who runs tools into someone who orchestrates entire operations. Every professional penetration tester, red teamer, and security engineer has Bash in their toolbox — and for good reason.

The journey from beginner to expert follows a clear path:

  1. Learn the basics — commands, variables, pipes, redirection.
  2. Practice daily — automate small tasks: file cleanup, log parsing, backups.
  3. Chain tools — combine Nmap, Gobuster, and Curl into workflows.
  4. Build your own scripts — port scanners, recon bots, log monitors.
  5. Study real code — read open-source pentest scripts on GitHub.
  6. Contribute back — share your tools with the community.

Remember: the terminal is your weapon, and Bash is your language. Master it, and you'll be able to build custom tooling that rivals commercial products — all with plain text and a shell.

🚀 Next Steps: Start small. Automate one repetitive task today. Then chain two tools together. Then build a full recon script. Before you know it, you'll be writing security tooling that other hackers use.

Happy hacking — ethically. 🐉