BASH scripting for hackers
If you want to get into hacking or penetration testing, bash scripting is one of the first things you should learn. It lets you automate boring tasks, build your own tools, and chain commands together in ways that will make your life so much easier. This guide walks you through everything from writing your very first script all the way to building real hacking tools like port scanners and brute forcers. No prior scripting experience needed - just a terminal and some curiosity.
Chapter 1: Your First Script
Let’s start with something simple. Open your terminal and follow along:
thilan@macbook:~/bash (master)$ ls
thilan@macbook:~/bash (master)$ vi script.sh
thilan@macbook:~/bash (master)$ ./script.sh
bash: ./script.sh: Permission denied
thilan@macbook:~/bash (master)$ chmod +x script.sh
thilan@macbook:~/bash (master)$ ./script.sh
hello world!
thilan@macbook:~/bash (master)$
What happened here?
- We created a file called
script.sh - We tried to run it, but got "Permission denied"
- We used
chmod +xto make it executable - Now it works!
Quick Tip: Always remember to make your scripts executable with chmod +x filename.sh
Chapter 2: Variables - Storing Information
Variables are like boxes where you store information. Here’s how:
x=1
echo \"value of x is $x\"
Output:
thilan@macbook:~/bash (master)$ ./script.sh
value of x is 1
Important Rule: No spaces around the = sign!
y = 5 # This will fail
y=5 # Correct
Using Variables with Text
name=\"Thilan\"
echo \"Hi ${name}, how are you?\"
The ${name} syntax is useful when you want to add text right after the variable.
Chapter 3: Getting User Input
Let’s make scripts interactive! Use read to ask questions:
read -p \"Enter your name: \" name
echo \"Hello $name\"
Try it yourself:
- Create a script that asks for your age
- Print "You are X years old"
Chapter 4: Making Decisions (If Statements)
Your scripts can make choices based on conditions:
x=10
if [ $x -gt 5 ]; then
echo \"x is greater than 5\"
elif [ $x -eq 5 ]; then
echo \"x is 5\"
else
echo \"x is less than 5\"
fi
Common Comparison Operators:
-eq→ equal to-ne→ not equal to-gt→ greater than-lt→ less than-ge→ greater or equal-le→ less or equal
Chapter 5: Loops - Doing Things Repeatedly
For Loop
for i in 1 2 3 4 5; do
echo \"Number $i\"
done
While Loop
count=1
while [ $count -le 5 ]; do
echo \"Count $count\"
((count++))
done
Challenge: Create a loop that counts from 10 down to 1 (countdown!)
Chapter 6: Functions - Reusable Code
Functions help you avoid repeating yourself:
greet() {
echo \"Hello $1\"
}
greet \"Thilan\"
The $1 means "first argument" passed to the function.
Chapter 7: Hacking Scripts - Real Examples
Now let’s build some useful hacking tools!
1. Port Scanner
#!/bin/bash
# Scan common ports on a target host
target=$1
for port in {20..25} 80 443 8080; do
timeout 1 bash -c \"echo >/dev/tcp/$target/$port\" 2>/dev/null && \
echo \"Port $port is open\"
done
How to use:
./portscan.sh 192.168.1.1
What it does:
- Checks if common ports are open
- Uses
/dev/tcp/(a bash feature to test TCP connections) timeout 1gives each check 1 second2>/dev/nullhides error messages
2. Password Brute Forcer
#!/bin/bash
# Try passwords from a file against HTTP Basic Auth
url=\"http://example.com\"
user=\"admin\"
while read -r password; do
response=$(curl -s -o /dev/null -w \"%{http_code}\" -u $user:$password $url)
if [ \"$response\" -eq 200 ]; then
echo \"[+] Password found: $password\"
break
fi
done < passwords.txt
What you need:
- A file called
passwords.txtwith one password per line - Target URL with basic authentication
Legal Warning: Only use this on systems you own or have permission to test!
3. URL Extractor
#!/bin/bash
# Grab all URLs from a webpage
url=$1
curl -s $url | grep -oP 'href=\"\K[^\"]+'
Usage:
./extract_urls.sh https://example.com
What it does:
- Downloads the webpage with
curl - Uses
grepwith regex to find all links -oPenables Perl-style regex for better pattern matching
4. Base64 Encoder/Decoder
#!/bin/bash
# Encode or decode text in base64
action=$1
text=$2
if [ \"$action\" == \"encode\" ]; then
echo -n \"$text\" | base64
elif [ \"$action\" == \"decode\" ]; then
echo -n \"$text\" | base64 --decode
else
echo \"Usage: $0 encode|decode <text>\"
fi
Usage:
./base64_tool.sh encode \"secret message\"
./base64_tool.sh decode \"c2VjcmV0IG1lc3NhZ2U=\"
Why is this useful?
- Many systems use base64 encoding
- Helps decode captured data
- Useful for bypassing basic filters
5. Subdomain Scanner
#!/bin/bash
# Checks which subdomains are alive
domain=$1
subdomains=(\"www\" \"test\" \"admin\" \"mail\" \"dev\" \"staging\")
for sub in \"${subdomains[@]}\"; do
host=\"$sub.$domain\"
if ping -c 1 -W 1 $host &>/dev/null; then
echo \"[+] $host is up\"
fi
done
Usage:
./subdomain_scan.sh example.com
Improve it: Add more subdomains to the list! Common ones include:
- api, vpn, ftp, blog, shop, portal
6. File Hunter
#!/bin/bash
# Find all .txt, .log, .bak files
dir=$1
echo \"Scanning $dir for sensitive files...\"
find $dir -type f \( -name \"*.txt\" -o -name \"*.log\" -o -name \"*.bak\" \)
Usage:
./file_hunter.sh /var/www/html
Why hunt these files?
.logfiles often contain errors and sensitive data.bakfiles are backups that might have passwords.txtfiles could contain notes or credentials
Chapter 8: Advanced Tricks
1. Command Substitution
Save command output to a variable:
current_user=$(whoami)
echo \"You are: $current_user\"
# Or grab IP address
my_ip=$(curl -s ifconfig.me)
echo \"Your IP: $my_ip\"
2. Arrays
Store multiple values:
targets=(\"192.168.1.1\" \"192.168.1.2\" \"192.168.1.3\")
for target in \"${targets[@]}\"; do
ping -c 1 $target
done
3. Piping and Redirecting
Chain commands together:
# Save output to file
nmap 192.168.1.1 > scan_results.txt
# Append to file
echo \"Scan completed\" >> scan_results.txt
# Pipe output to another command
cat passwords.txt | grep \"admin\"
4. Check if File Exists
if [ -f \"passwords.txt\" ]; then
echo \"File exists!\"
else
echo \"File not found\"
fi
Other checks:
-d→ check if directory exists-x→ check if file is executable-w→ check if file is writable
Chapter 9: Practice Challenges
Challenge 1: Network Alive Checker
Create a script that:
- Takes a subnet (like 192.168.1)
- Pings all addresses from .1 to .254
- Lists which ones are alive
Challenge 2: Password Generator
Create a script that:
- Asks how many passwords to generate
- Asks for password length
- Creates random passwords and saves them to a file
Hint: Use /dev/urandom and tr command
Challenge 3: Log Analyzer
Create a script that:
- Reads a log file
- Counts how many times each IP address appears
- Shows the top 5 most common IPs
Chapter 10: Best Practices
1. Always Start with Shebang
#!/bin/bash
This tells the system to use bash to run your script.
2. Add Comments
# This function scans ports
# Usage: scan_ports <target>
Good comments help you remember what your code does.
3. Use Meaningful Variable Names
# Bad
x=\"192.168.1.1\"
# Good
target_ip=\"192.168.1.1\"
4. Check for Required Arguments
if [ $# -eq 0 ]; then
echo \"Usage: $0 <target>\"
exit 1
fi
5. Handle Errors
if ! command -v nmap &> /dev/null; then
echo \"Error: nmap is not installed\"
exit 1
fi
Wrapping Up
That covers pretty much everything you need to get started with bash scripting as a hacker. The real key is practice - take the scripts from Chapter 7, modify them, break them, and build your own. Once you get comfortable chaining commands together and automating tasks, you will start seeing opportunities to write scripts everywhere. And honestly, that is when things get really fun.