BASH scripting for hackers
Thilan Dissanayaka Penetration Testing June 08, 2020

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 +x to 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:

  1. Create a script that asks for your age
  2. 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 1 gives each check 1 second
  • 2>/dev/null hides 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.txt with 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 grep with regex to find all links
  • -oP enables 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?

  • .log files often contain errors and sensitive data
  • .bak files are backups that might have passwords
  • .txt files 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:

  1. Takes a subnet (like 192.168.1)
  2. Pings all addresses from .1 to .254
  3. Lists which ones are alive

Challenge 2: Password Generator

Create a script that:

  1. Asks how many passwords to generate
  2. Asks for password length
  3. Creates random passwords and saves them to a file

Hint: Use /dev/urandom and tr command

Challenge 3: Log Analyzer

Create a script that:

  1. Reads a log file
  2. Counts how many times each IP address appears
  3. 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.

ALSO READ
Blockchain 0x000 – Understanding the Fundamentals
May 21, 2020 Web3 Development

Imagine a world where strangers can exchange money, share data, or execute agreements without ever needing to trust a central authority. No banks, no intermediaries, no single point of failure yet...

Identity and Access Management (IAM)
May 11, 2020 Identity & Access Management

Who are you — and what are you allowed to do? That's the fundamental question every secure system must answer. And it's exactly what Identity and Access Management (IAM) is built to solve.

How I built a web based CPU Simulator
May 07, 2020 Pet Projects

As someone passionate about computer engineering, reverse engineering, and system internals, I've always been fascinated by what happens "under the hood" of a computer. This curiosity led me to...

Writing a Shell Code for Linux
Apr 21, 2020 Exploit Development

Shellcode is a small piece of machine code used as the payload in exploit development. In this post, we write Linux shellcode from scratch — starting with a simple exit, building up to spawning a shell, and explaining every decision along the way.

Exploiting a Stack Buffer Overflow on Windows
Apr 12, 2020 Exploit Development

In a previous tutorial we discusses how we can exploit a buffer overflow vulnerability on a Linux machine. I wen through all theories in depth and explained each step. Now today we are going to jump...

Access Control Models
Apr 08, 2020 Identity & Access Management

Access control is one of the most fundamental concepts in security. Every time you set file permissions, assign user roles, or restrict access to a resource, you're implementing some form of access control. But not all access control is created equal...

Exploiting a  Stack Buffer Overflow  on Linux
Apr 01, 2020 Exploit Development

Have you ever wondered how attackers gain control over remote servers? How do they just run some exploit and compromise a computer? If we dive into the actual context, there is no magic happening....

Basic concepts of Cryptography
Mar 01, 2020 Cryptography

Ever notice that little padlock icon in your browser's address bar? That's cryptography working silently in the background, protecting everything you do online. Whether you're sending an email,...

Common Web Application Attacks
Feb 05, 2020 Application Security

Web applications are one of the most targeted surfaces by attackers. This is primarily because they are accessible over the internet, making them exposed and potentially vulnerable. Since these...

Remote Code Execution (RCE)
Jan 02, 2020 Application Security

Remote Code Execution (RCE) is the holy grail of application security vulnerabilities. It allows an attacker to execute arbitrary code on a remote server — and the consequences are as bad as it sounds. In this post, we'll go deep into RCE across multiple languages, including PHP, Java, Python, and Node.js.