Bash Scripting Basics for Hackers

⚠️ Safety & Ethics

Bash scripting is a force multiplier — it saves time and helps repeat checks reliably. Use the skills and scripts in controlled lab environments or on systems you own / are authorized to test. Do not use them to attack or scan other people’s networks without permission.

🧠 Why learn Bash as a hacker?

  • Automates repetitive reconnaissance and hardening tasks.

  • Lets you glue together multiple tools into a single workflow.

  • Runs on virtually every Linux system (no extra dependencies).

  • Helps you write quick proof-of-concepts, audit scripts, and defensive checks.

We’ll start with the basics and build toward practical scripts you can run in a VM lab.

📚 Bash fundamentals (quick reference)

Shebang & execution

				
					#!/usr/bin/env bash
# Make this script executable: chmod +x script.sh
# Run: ./script.sh

				
			

Variables

				
					NAME="HackThatShit"
COUNT=5
echo "Welcome, $NAME — running $COUNT checks"

				
			

Command substitution

				
					HOST=$(hostname)
NOW=$(date +%F_%T)

				
			

Conditionals

				
					if [[ -f "/etc/passwd" ]]; then
  echo "passwd exists"
else
  echo "No passwd file found"
fi

				
			

Loops

				
					for i in 1 2 3; do
  echo "Item $i"
done

while read -r line; do
  echo "$line"
done < file.txt

				
			

Functions

				
					log() {
  echo "[$(date +%T)] $*"
}
log "Starting script"

				
			

Exit codes & error handling

				
					set -euo pipefail  # fail on error, undefined var, and pipe errors
trap 'echo "Script failed at line $LINENO"; exit 1' ERR

				
			

🧰 Practical, lab-safe scripts

Below are three useful scripts you can use in your VM labs. They are defensive/educational: they enumerate, summarize, and save results. Save each as *.sh, chmod +x them, and run only in authorized environments.

Quick System Inventory (safe)

Collects basic system info for triage.

				
					#!/usr/bin/env bash
set -euo pipefail

OUTDIR="./lab_inventory_$(date +%F_%H%M%S)"
mkdir -p "$OUTDIR"

echo "Saving system inventory to $OUTDIR"

hostname > "$OUTDIR/hostname.txt"
uname -a > "$OUTDIR/uname.txt"
cat /etc/os-release > "$OUTDIR/os_release.txt" || true
whoami > "$OUTDIR/whoami.txt"
id > "$OUTDIR/id.txt"
ps aux --sort=-%mem | head -n 30 > "$OUTDIR/top_processes.txt"

echo "Inventory complete."

				
			

What it’s for: Fast snapshot of a lab VM before you begin experiments.

Permission & SUID Summary (audit-style)

Lists SUID/SGID files and world-writable dirs — lab-only.

				
					#!/usr/bin/env bash
set -euo pipefail

OUT="./permission_audit_$(date +%F_%H%M%S).txt"
echo "Permission audit - $(date)" > "$OUT"

echo -e "\n== SUID/SGID files ==" >> "$OUT"
find / -xdev -perm -4000 -o -perm -2000 -type f 2>/dev/null >> "$OUT"

echo -e "\n== World-writable directories ==" >> "$OUT"
find / -xdev -perm -o+w -type d 2>/dev/null >> "$OUT"

echo -e "\n== /etc/sudoers and /etc/sudoers.d ==" >> "$OUT"
sudo cat /etc/sudoers 2>/dev/null || echo "/etc/sudoers unreadable" >> "$OUT"
ls -la /etc/sudoers.d 2>/dev/null >> "$OUT"

echo "Audit saved to $OUT"

				
			

Safety note: Uses find on the root filesystem — run only in VMs you control. -xdev limits the search to the same filesystem and reduces noise.

Simple Recon Wrapper (lab-only, respectful scanning)

A tiny wrapper that runs benign checks and a local-only nmap quick scan. Do not target external networks without permission.

				
					#!/usr/bin/env bash
set -euo pipefail

TARGET=${1:-127.0.0.1}   # default to localhost
OUTDIR="./recon_$(date +%F_%H%M%S)_${TARGET//:/_}"
mkdir -p "$OUTDIR"

echo "Recon for $TARGET — results in $OUTDIR"

# banner + tcp ports (quick)
echo "### uname ###" > "$OUTDIR/recon.txt"
uname -a >> "$OUTDIR/recon.txt"

echo -e "\n### listening sockets ###" >> "$OUTDIR/recon.txt"
ss -tulwn >> "$OUTDIR/recon.txt"

# nmap quick scan - local-only by default
if command -v nmap >/dev/null 2>&1; then
  echo -e "\n### nmap quick ###" >> "$OUTDIR/recon.txt"
  # IMPORTANT: Respect policies — do not scan networks you don't own.
  nmap -sC -sV -oN "$OUTDIR/nmap_quick.txt" "$TARGET" || echo "nmap failed or incomplete" >> "$OUTDIR/recon.txt"
else
  echo "nmap not installed" >> "$OUTDIR/recon.txt"
fi

echo "Recon complete."

				
			

Usage: ./recon.sh (defaults to localhost) or ./recon.sh 10.0.2.15 in your lab network only.

🧪 Exercises — practice these in your lab

  • Write a script that checks for new users — compare /etc/passwd snapshots and email (or log) changes.

  • Automate the permission audit to run daily and rotate output files — add simple alerting when SUID/SGID count increases.

  • Create a script that runs safe updates (sudo apt update && sudo apt upgrade -y) with logging and dry-run flags.

  • Make a modular script: build small reusable functions (e.g., gather_sysinfo, audit_permissions, run_recon) and combine them in one driver script.

  • Add argument parsing: support --targets, --outdir, and --skip-nmap flags using getopts.

🛠️ Best practices for hacker scripts (and safety)

  • Always add set -euo pipefail at the top for safer failures.

  • Use absolute paths for important binaries (e.g., /usr/bin/nmap) when running in privileged contexts.

  • Validate inputs (never trust user-supplied targets if running privileged).

  • Log outputs with timestamps and rotate logs to avoid filling disks.

  • Always include usage/help output (-h/--help).

  • Keep scripts idempotent: running them twice should not cause problems.

  • Version-control your scripts and review changes before running on important systems.

📦 How this helps the series

Bash lets you automate the defensive checks and lab enumeration we covered in Parts 4–6. In Part 8 we’ll put scripting into practice by building real, safe recon & exploit-helper scripts (focused on lab automation and defensive auditing, not on attacking production systems).

🎯 Coming Up Next

Part 8: Writing Exploit & Recon Scripts in Bash — we’ll create modular scripts to automate multi-step lab workflows (e.g., combined enumeration → suggestion → remediation), and I’ll provide downloadable templates.

💬 Got Questions?

Drop them in the comments or join our community on Discord for exclusive hacking tips and resources.


Don’t worry — mastery comes with practice.
Just open your terminal and hack your brain into CLI mode daily.

Let’s keep building. 💻⚔️

Leave a comment

Index