The Complete Beginner's Guide to Bash Scripting: From Zero to Hacker Hero
Chapter 1: Welcome to the World of Scripting
Picture this: you're sitting at your computer, typing the same commands over and over again. Your fingers are getting tired, your eyes are glazing over, and you're thinking there has to be a better way. Well, my friend, there absolutely is, and it's called scripting.
Think of scripting as teaching your computer to do your repetitive tasks while you grab a coffee and watch it work its magic. It's like having a digital assistant that never complains, never gets tired, and executes your commands with perfect precision every single time.
Every successful hacker and system administrator knows that scripting isn't just a nice-to-have skill – it's absolutely essential. Whether you're automating security scans, managing system configurations, or analyzing data, scripts are your secret weapon for getting things done efficiently and effectively.
In this comprehensive guide, we're going to embark on a journey together. We'll start with the absolute basics, assuming you've never written a single line of code in your life, and gradually build up to creating powerful tools that can scan networks, analyze systems, and automate complex tasks. By the time you finish this book, you'll have the confidence and skills to tackle any scripting challenge that comes your way.
Chapter 2: Understanding Your Digital Workspace
Before we dive into writing our first script, let's talk about what we're actually working with. When you open a terminal or command prompt, you're not just staring at a blank screen – you're looking at one of the most powerful interfaces ever created.
The shell is your gateway to the heart of your computer's operating system. It's where the real magic happens, away from all those pretty buttons and icons of graphical interfaces. Think of it as having a direct conversation with your computer in its native language.
Now, there are several different shells available, each with its own personality and quirks. You've got the Korn shell, the Z shell, the C shell, and our star of the show – the Bourne-again shell, affectionately known as bash. While newer systems might default to other shells, bash remains the gold standard that most systems understand and support.
If you're using Kali Linux and find yourself in the Z shell, don't worry. We can easily switch back to bash using a simple command called kali-tweaks. This opens up a user-friendly menu where you can navigate to the shell settings and select bash as your default. It's like choosing your preferred language for having conversations with your computer.
The beauty of bash is its universality. Whether you're working on Red Hat, Ubuntu, Solaris, or countless other Unix-like systems, bash is there, ready to interpret your commands and execute your scripts with reliability and consistency.
Chapter 3: Essential Tools and Commands
Before we start building our scripting empire, we need to familiarize ourselves with some fundamental tools that will become your best friends throughout this journey.
First up is the echo command, which is beautifully simple in its purpose. It takes whatever you give it and displays it right back to you on the screen. Think of it as your computer's way of saying "I heard you loud and clear." When you want your script to communicate with users or display information, echo is your go-to companion.
Then there's the read command, which does exactly the opposite of echo. Instead of outputting information, it waits patiently for input from the user. It's like your script politely asking, "What would you like me to do?" and then remembering the answer for later use.
You'll also need a trusty text editor to craft your scripts. This isn't about fancy formatting or colorful fonts – we're dealing with pure, unadorned text. Popular choices among hackers and system administrators include vi, vim, emacs, gedit, and kate. Each has its own devoted following, but for our purposes, any plain text editor will serve you well. The key is finding one you're comfortable with and sticking with it.
These tools might seem simple individually, but when combined thoughtfully in a script, they become incredibly powerful. It's like having a basic set of tools that can build anything from a simple birdhouse to a magnificent cathedral – it all depends on how creatively and skillfully you use them.
Chapter 4: Your First Steps into Scripting
Let's create something together right now. Open your text editor and let's build your very first script. We're going to create a program that simply says "Hello, Hackers-Arise!" to the world.
Every script needs to start with what's called a shebang. This isn't some mystical incantation – it's simply a hash mark followed by an exclamation mark: #!. This tells your operating system which interpreter to use for your script. Since we're working with bash, we follow the shebang with /bin/bash.
So your script starts like this:
#!/bin/bash
Next, let's add a comment to explain what our script does. Comments are lines that start with a hash mark, and they're your notes to yourself and anyone else who might read your code. The computer completely ignores them, but they're invaluable for understanding what's happening in your script, especially when you come back to it weeks or months later.
#!/bin/bash
# This is my first bash script. Wish me luck.
Now comes the exciting part – making your script actually do something. We'll use the echo command to display our message:
#!/bin/bash
# This is my first bash script. Wish me luck.
echo "Hello, Hackers-Arise!"
Save this file as HelloHackersArise (notice no file extension – we don't need one for bash scripts, though you can add .sh if you prefer).
But wait, we're not done yet. Your newly created script isn't executable by default. This is a security feature – the system wants to make sure you really intend for this file to be run as a program. We need to give ourselves permission to execute it using the chmod command:
chmod 755 HelloHackersArise
Now you can run your script by typing:
./HelloHackersArise
The "./" tells the system to look for the file in your current directory. When you press enter, you should see "Hello, Hackers-Arise!" displayed on your screen. Congratulations! You've just written and executed your first bash script.
Chapter 5: Adding Intelligence with Variables
Our first script was nice, but it was pretty static. Real-world scripts need to be dynamic and responsive. This is where variables come into play, and they're going to transform your scripting from basic to brilliant.
A variable is like a labeled box where you can store information. You can put text, numbers, or even the results of commands into these boxes, and then use that information throughout your script. The beautiful thing about variables is that their contents can change (hence the name "variable"), making your scripts adaptable and interactive.
Let's create a more sophisticated script that actually interacts with the user. This script will ask for the user's name and what chapter they're currently reading, then create a personalized welcome message.
#!/bin/bash
# This script demonstrates user input and variables
echo "What is your name?"
read name
echo "What chapter are you on in Linux Basics for Hackers?"
read chapter
echo "Welcome $name to Chapter $chapter of Linux Basics for Hackers!"
Here's what's happening in this script: First, we ask the user for their name using echo, then we capture their response using read and store it in a variable called name. We do the same thing for the chapter number, storing it in a variable called chapter.
The magic happens in the final line where we use these variables to create a personalized message. Notice how we put a dollar sign ($) in front of the variable names? That's how we tell bash that we want to use the value stored in the variable, not just print the word "name" or "chapter" literally.
Save this as WelcomeScript.sh, make it executable with chmod 755, and run it. You'll see how your script now has a conversation with the user, remembers what they tell it, and uses that information to create a customized response. This is the foundation of interactive scripting.
Chapter 6: Real-World Application – Network Scanning
Now that you understand the basics, let's tackle something with real practical value. We're going to create a script that can scan networks looking for open ports – a fundamental skill in cybersecurity and system administration.
But first, we need to talk about a powerful tool called nmap. This network mapper is like a digital detective that can probe systems to see what services are running and what ports are open. Understanding what ports are open on a system tells you what services are available, which is crucial information for both security professionals and potential attackers.
The basic syntax for nmap is straightforward:
nmap <type of scan> <target IP> <optionally, target port>
For example, to perform a TCP scan of IP address 192.168.1.1 looking for MySQL database servers (which typically run on port 3306), you would use:
nmap -sT 192.168.1.1 -p 3306
Now let's create a script that automates this process. Our goal is to scan a range of IP addresses looking for systems running MySQL databases.
#!/bin/bash
# This script finds hosts with MySQL installed
nmap -sT 192.168.181.0/24 -p 3306 >/dev/null -oG MySQLscan
cat MySQLscan | grep open > MySQLscan2
cat MySQLscan2
This script does several clever things. First, it runs an nmap scan on an entire subnet (the /24 means scan all 254 possible addresses in that range). The ">/dev/null" part sends the normal nmap output to nowhere – it disappears – because we only want to see the final results, not all the scanning details.
The "-oG MySQLscan" tells nmap to save its results in a grep-friendly format to a file called MySQLscan. Then we use grep to filter out only the lines that contain the word "open" – these are the systems with MySQL running.
Chapter 7: Making Scripts User-Friendly and Flexible
Our network scanner works, but it's not very flexible. What if you want to scan a different network range? What if you're looking for a different service on a different port? You'd have to edit the script every time, which defeats the purpose of automation.
Let's upgrade our script to make it interactive and flexible:
#!/bin/bash
echo "Enter the starting IP address: "
read FirstIP
echo "Enter the last octet of the last IP address: "
read LastOctetIP
echo "Enter the port number you want to scan for: "
read port
nmap -sT $FirstIP-$LastOctetIP -p $port >/dev/null -oG MySQLscan
cat MySQLscan | grep open > MySQLscan2
cat MySQLscan2
This upgraded version asks the user for three pieces of information: the starting IP address, the ending range (just the last number), and which port to scan for. This makes the script incredibly versatile – you can use it to scan for web servers (port 80), email servers (port 25), or any other service you're interested in.
When you run this script, it might look like this:
Enter the starting IP address:
192.168.1.1
Enter the last octet of the last IP address:
254
Enter the port number you want to scan for:
22
Host: 192.168.1.50 () Ports: 22/open/tcp//ssh//
Host: 192.168.1.100 () Ports: 22/open/tcp//ssh//
This output tells you that two systems in your network have SSH (Secure Shell) running on port 22, which is valuable information for network administration and security assessment.
Chapter 8: Understanding the Anatomy of Professional Scripts
As your scripts become more sophisticated, you'll need to understand the various components that make them robust and maintainable. Professional scripts aren't just about getting the job done – they're about doing it reliably, efficiently, and in a way that others can understand and modify.
Comments are your first line of defense against confusion. When you're writing a script, everything seems crystal clear. But come back to that same script six months later, and you might find yourself scratching your head wondering what you were thinking. Good comments explain not just what the code does, but why it does it.
Variable naming is another crucial aspect of professional scripting. While you could name your variables x, y, and z, it's much better to use descriptive names like username, target_ip, and scan_results. This makes your scripts self-documenting and much easier to maintain.
Error handling is something many beginners overlook, but it's essential for robust scripts. What happens if the user enters an invalid IP address? What if the target system doesn't respond? Professional scripts anticipate these scenarios and handle them gracefully, providing useful feedback to the user instead of just crashing.
Chapter 9: Advanced Variable Techniques
Variables can do much more than just store simple text or numbers. They can hold the results of commands, perform calculations, and even store complex data structures. Understanding these advanced techniques will elevate your scripting to the next level.
Command substitution allows you to store the output of a command in a variable. For example:
current_date=$(date)
current_user=$(whoami)
echo "Script run by $current_user on $current_date"
This technique is incredibly powerful because it lets your scripts adapt to their environment dynamically. You can capture system information, process file contents, or store the results of network commands for later use.
Arrays are another advanced feature that lets you store multiple values in a single variable. Think of an array as a numbered list where you can store related items:
servers=("web1.example.com" "web2.example.com" "db1.example.com")
for server in "${servers[@]}"; do
ping -c 1 "$server"
done
This script would ping each server in the array, making it easy to check the status of multiple systems with a single script.
Chapter 10: Control Structures – Making Decisions
Real-world scripts need to make decisions based on conditions and repeat actions when necessary. This is where control structures come in – they're the logic that makes your scripts intelligent.
Conditional statements (if/then/else) allow your scripts to take different actions based on circumstances:
#!/bin/bash
echo "Enter the IP address to check:"
read target_ip
if ping -c 1 "$target_ip" >/dev/null 2>&1; then
echo "$target_ip is reachable"
echo "Running port scan..."
nmap -sT "$target_ip"
else
echo "$target_ip is not reachable"
echo "Please check the IP address and network connection"
fi
This script first tests whether a target system responds to ping. If it does, it proceeds with a port scan. If not, it informs the user that the system isn't reachable. This kind of logic makes your scripts much more user-friendly and robust.
Loops allow your scripts to repeat actions efficiently. Instead of copying and pasting the same code multiple times, you can use a loop:
#!/bin/bash
echo "Scanning common ports on multiple hosts..."
hosts=("192.168.1.1" "192.168.1.10" "192.168.1.20")
ports=("22" "80" "443")
for host in "${hosts[@]}"; do
echo "Scanning $host"
for port in "${ports[@]}"; do
if nmap -p "$port" "$host" | grep -q "open"; then
echo " Port $port is open on $host"
fi
done
done
This script demonstrates nested loops – one loop goes through each host, and for each host, another loop checks multiple ports. It's like having a systematic method for checking every combination of hosts and ports.
Chapter 11: Functions – Organizing Your Code
As your scripts grow longer and more complex, you'll find yourself repeating certain patterns of code. Functions allow you to package commonly used code into reusable blocks, making your scripts cleaner and more maintainable.
A function is like a mini-script within your script. You define it once, then call it whenever you need its functionality:
#!/bin/bash
# Define a function to check if a port is open
check_port() {
local host=$1
local port=$2
if nmap -p "$port" "$host" | grep -q "open"; then
echo "Port $port is OPEN on $host"
return 0
else
echo "Port $port is CLOSED on $host"
return 1
fi
}
# Use the function
echo "Enter host to scan:"
read target_host
check_port "$target_host" 22
check_port "$target_host" 80
check_port "$target_host" 443
Functions make your code more modular and easier to debug. If there's a problem with how port checking works, you only need to fix it in one place – the function definition – rather than hunting through your entire script for every instance of that code.
Chapter 12: File Operations and Data Processing
Most real-world scripts need to work with files – reading configuration data, processing log files, or storing results for later analysis. Bash provides powerful tools for file manipulation that can save you countless hours of manual work.
Reading files line by line is a common requirement:
#!/bin/bash
echo "Processing server list..."
while IFS= read -r server; do
echo "Checking server: $server"
if ping -c 1 "$server" >/dev/null 2>&1; then
echo "$server is online"
nmap -sT "$server" -p 22,80,443 | grep "open"
else
echo "$server is offline"
fi
done < servers.txt
This script reads a list of server names from a file called servers.txt and performs connectivity checks on each one. The power of this approach is that you can maintain your server list in a separate file and update it without modifying the script.
Text processing is another area where bash excels. You can search, filter, and transform text data with tools like grep, sed, and awk:
#!/bin/bash
echo "Analyzing log file for security events..."
# Count failed login attempts
failed_logins=$(grep "Failed password" /var/log/auth.log | wc -l)
echo "Failed login attempts: $failed_logins"
# Extract unique IP addresses from failed attempts
echo "Top attacking IP addresses:"
grep "Failed password" /var/log/auth.log | \
grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | \
sort | uniq -c | sort -nr | head -10
This script analyzes authentication logs to identify potential security threats, demonstrating how bash can be used for security monitoring and incident response.
Chapter 13: Advanced Network Scanning Techniques
Building on our earlier network scanning examples, let's explore more sophisticated techniques that professional penetration testers and system administrators use.
Port scanning is just the beginning. Modern network assessment requires understanding different types of scans and when to use them:
#!/bin/bash
echo "Advanced Network Scanner"
echo "======================="
scan_tcp_connect() {
echo "Running TCP Connect scan..."
nmap -sT "$1" -p "$2" --open
}
scan_syn() {
echo "Running SYN scan (requires root)..."
sudo nmap -sS "$1" -p "$2" --open
}
scan_udp() {
echo "Running UDP scan (slow but thorough)..."
sudo nmap -sU "$1" -p "$2" --open
}
echo "Enter target IP or range:"
read target
echo "Enter port range (e.g., 1-1000):"
read ports
echo "Select scan type:"
echo "1) TCP Connect (safe, no root required)"
echo "2) SYN scan (fast, requires root)"
echo "3) UDP scan (slow, requires root)"
read -p "Choice: " choice
case $choice in
1) scan_tcp_connect "$target" "$ports" ;;
2) scan_syn "$target" "$ports" ;;
3) scan_udp "$target" "$ports" ;;
*) echo "Invalid choice" ;;
esac
This script demonstrates several important concepts: functions for code organization, user input validation, and the case statement for handling multiple options elegantly.
Chapter 14: Automating Security Tasks
Security professionals rely heavily on automation to monitor systems, analyze logs, and respond to threats. Let's build some practical security-focused scripts.
A system monitoring script might check for various security indicators:
#!/bin/bash
echo "=== System Security Check ==="
echo "Date: $(date)"
echo
# Check for users with empty passwords
echo "Checking for users with empty passwords..."
empty_pass=$(sudo awk -F: '($2 == "") {print $1}' /etc/shadow)
if [ -n "$empty_pass" ]; then
echo "WARNING: Users with empty passwords found: $empty_pass"
else
echo "OK: No users with empty passwords"
fi
# Check for world-writable files
echo
echo "Checking for world-writable files in sensitive directories..."
world_writable=$(find /etc /usr/bin /usr/sbin -type f -perm -002 2>/dev/null)
if [ -n "$world_writable" ]; then
echo "WARNING: World-writable files found:"
echo "$world_writable"
else
echo "OK: No world-writable files in critical directories"
fi
# Check disk usage
echo
echo "Checking disk usage..."
df -h | awk '$5+0 > 80 {print "WARNING: " $1 " is " $5 " full"}'
This script performs several security checks automatically, making it easy to run regular system audits without manual intervention.
Chapter 15: Error Handling and Robust Scripting
Professional scripts need to handle errors gracefully and provide useful feedback when things go wrong. This separates amateur scripts from production-ready tools.
Here's an example of robust error handling:
#!/bin/bash
# Function to display error messages
error_exit() {
echo "ERROR: $1" >&2
exit 1
}
# Function to check if required tools are available
check_dependencies() {
for tool in nmap nc ping; do
if ! command -v "$tool" >/dev/null 2>&1; then
error_exit "$tool is required but not installed"
fi
done
}
# Validate IP address format
validate_ip() {
if [[ ! $1 =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
error_exit "Invalid IP address format: $1"
fi
}
# Main script
echo "Network Connectivity Checker"
echo "============================"
check_dependencies
echo "Enter target IP address:"
read -r target_ip
validate_ip "$target_ip"
echo "Testing connectivity to $target_ip..."
if ping -c 3 "$target_ip" >/dev/null 2>&1; then
echo "✓ Host is reachable via ping"
echo "Scanning common ports..."
nmap -sT "$target_ip" -p 22,80,443,3389 --open 2>/dev/null | grep "open" || echo "No common ports found open"
else
echo "✗ Host is not reachable via ping"
echo "This could indicate:"
echo " - Host is down"
echo " - Host blocks ping"
echo " - Network connectivity issues"
fi
This script includes comprehensive error checking, dependency validation, and clear user feedback, making it suitable for professional use.
Chapter 16: Working with APIs and Web Services
Modern systems often need to interact with web APIs to gather information or trigger actions. Bash can handle these tasks using tools like curl and wget.
Here's a script that checks website availability and gathers basic information:
#!/bin/bash
check_website() {
local url=$1
local timeout=10
echo "Checking $url..."
# Check if site responds
if curl -s --max-time $timeout "$url" >/dev/null; then
echo "✓ Site is responding"
# Get HTTP status code
status_code=$(curl -s -o /dev/null -w "%{http_code}" --max-time $timeout "$url")
echo " Status code: $status_code"
# Get response time
response_time=$(curl -s -o /dev/null -w "%{time_total}" --max-time $timeout "$url")
echo " Response time: ${response_time}s"
# Check for specific technologies
if curl -s --max-time $timeout "$url" | grep -qi "wordpress"; then
echo " Technology: WordPress detected"
fi
else
echo "✗ Site is not responding"
fi
echo
}
echo "Website Availability Checker"
echo "=========================="
# Check multiple sites
websites=("https://google.com" "https://github.com" "https://stackoverflow.com")
for site in "${websites[@]}"; do
check_website "$site"
done
# Allow user to check custom site
echo "Enter a custom URL to check (or press Enter to skip):"
read -r custom_url
if [ -n "$custom_url" ]; then
check_website "$custom_url"
fi
This script demonstrates how to interact with web services, parse responses, and present information in a user-friendly format.
Chapter 17: Log Analysis and Monitoring
System logs contain wealth of information, but manually analyzing them is time-consuming and error-prone. Scripts can automate this process and highlight important events.
#!/bin/bash
echo "System Log Analysis Report"
echo "========================="
echo "Generated: $(date)"
echo
# Analyze authentication logs
if [ -f "/var/log/auth.log" ]; then
echo "=== Authentication Analysis ==="
# Successful logins today
successful_logins=$(grep "$(date '+%b %d')" /var/log/auth.log | grep "Accepted" | wc -l)
echo "Successful logins today: $successful_logins"
# Failed login attempts today
failed_logins=$(grep "$(date '+%b %d')" /var/log/auth.log | grep "Failed" | wc -l)
echo "Failed login attempts today: $failed_logins"
# Top 5 source IPs for failed logins
echo
echo "Top source IPs for failed logins:"
grep "$(date '+%b %d')" /var/log/auth.log | \
grep "Failed" | \
grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' | \
sort | uniq -c | sort -nr | head -5
echo
fi
# System resource analysis
echo "=== System Resource Status ==="
echo "CPU Load: $(uptime | awk -F'load average:' '{print $2}')"
echo "Memory Usage:"
free -h | grep Mem | awk '{printf " Used: %s / %s (%.1f%%)\n", $3, $2, ($3/$2)*100}'
echo "Disk Usage:"
df -h | awk 'NR>1 {if($5+0 > 80) printf " WARNING: %s is %s full\n", $1, $5; else printf " OK: %s is %s full\n", $1, $5}'
echo
echo "=== Recent System Events ==="
journalctl --since "1 hour ago" --priority=err --no-pager -q | head -10
This script provides a comprehensive overview of system health and security events, making it easy to spot potential issues quickly.
Chapter 18: Database Interaction and Data Management
Many scripts need to work with databases to store results, retrieve configuration data, or perform analysis. Here's how to interact with MySQL databases from bash scripts:
#!/bin/bash
# Database configuration
DB_HOST="localhost"
DB_NAME="monitoring"
DB_USER="monitor"
DB_PASS="password"
# Function to execute SQL queries
execute_sql() {
mysql -h "$DB_HOST" -u "$DB_USER" -p"$DB_PASS" "$DB_NAME" -e "$1" 2>/dev/null
}
# Function to check database connectivity
check_db_connection() {
if execute_sql "SELECT 1;" >/dev/null; then
echo "✓ Database connection successful"
return 0
else
echo "✗ Database connection failed"
return 1
fi
}
# Function to log scan results
log_scan_result() {
local target=$1
local port=$2
local status=$3
local timestamp=$(date '+%Y-%m-%d %H:%M:%S')
sql="INSERT INTO scan_results (timestamp, target, port, status) VALUES ('$timestamp', '$target', '$port', '$status');"
execute_sql "$sql"
}
echo "Network Scanner with Database Logging"
echo "===================================="
# Check database connection
if ! check_db_connection; then
echo "Cannot proceed without database connection"
exit 1
fi
echo "Enter target IP:"
read -r target_ip
echo "Scanning common ports on $target_ip..."
# Scan common ports and log results
for port in 22 80 443 3389; do
echo -n "Scanning port $port... "
if nmap -p "$port" "$target_ip" | grep -q "open"; then
echo "OPEN"
log_scan_result "$target_ip" "$port" "open"
else
echo "CLOSED"
log_scan_result "$target_ip" "$port" "closed"
fi
done
echo
echo "Recent scan history:"
execute_sql "SELECT timestamp, target, port, status FROM scan_results ORDER BY timestamp DESC LIMIT 10;"
This script demonstrates how to integrate database operations into your network scanning workflow, providing persistent storage and historical analysis capabilities.
Chapter 19: Parallel Processing and Performance Optimization
When scanning large networks or processing many files, sequential processing can be painfully slow. Bash supports parallel processing techniques that can dramatically improve performance.
#!/bin/bash
# Function to scan a single host
scan_host() {
local host=$1
local output_file="scan_${host//\./_}.tmp"
echo "Scanning $host..." >&2
# Ping test
if ping -c 1 -W 2 "$host" >/dev/null 2>&1; then
echo "$host,online,$(date)" > "$output_file"
# Quick port scan
open_ports=$(nmap -T4 --top-ports 100 "$host" 2>/dev/null | grep "open" | wc -l)
echo "$host has $open_ports open ports" >&2
echo "$host,$open_ports,$(date)" >> "$output_file"
else
echo "$host,offline,$(date)" > "$output_file"
fi
}
# Export function so background processes can use it
export -f scan_host
echo "Parallel Network Scanner"
echo "======================="
# Generate IP range
echo "Enter network (e.g., 192.168.1):"
read -r network
echo "Generating IP list..."
for i in {1..254}; do
echo "${network}.${i}"
done > ip_list.txt
echo "Starting parallel scans..."
# Launch background processes (limit to 20 concurrent jobs)
cat ip_list.txt | xargs -n 1 -P 20 -I {} bash -c 'scan_host "$@"' _ {}
echo "Waiting for all scans to complete..."
wait
echo
echo "Consolidating results..."
# Combine all temporary files
cat scan_*.tmp > full_results.txt
rm -f scan_*.tmp ip_list.txt
echo "Results summary:"
online_hosts=$(grep ",online," full_results.txt | wc -l)
offline_hosts=$(grep ",offline," full_results.txt | wc -l)
echo "Online hosts: $online_hosts"
echo "Offline hosts: $offline_hosts"
echo
echo "Hosts with open ports:"
grep -E ",[0-9]+," full_results.txt | sort -t, -k2 -nr | head -10
This script uses xargs with the -P flag to run multiple scans in parallel, significantly reducing the time required to scan large networks.
Chapter 20: Advanced Text Processing and Regular Expressions
Text processing is one of bash's greatest strengths. Understanding regular expressions and advanced text manipulation techniques opens up powerful possibilities for data analysis and system administration.
#!/bin/bash
echo "Advanced Log Analysis Tool"
echo "========================="
# Function to analyze web server logs
analyze_web_logs() {
local log_file=$1
if [ ! -f "$log_file" ]; then
echo "Log file not found: $log_file"
return 1
fi
echo "Analyzing $log_file..."
echo
# Extract and count unique IP addresses
echo "=== Top 10 IP Addresses ==="
grep -oE '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' "$log_file" | \
sort | uniq -c | sort -nr | head -10 | \
while read count ip; do
printf "%-15s %s requests\n" "$ip" "$count"
done
echo
# Extract HTTP status codes
echo "=== HTTP Status Codes ==="
awk '{print $9}' "$log_file" |
Wow—look at how far you’ve come! What started as a simple “Hello, Hackers-Arise!” script has turned into a solid foundation in Bash scripting. You now have the power to automate tasks, solve real problems, and even build your own tools when none exist. That’s no small feat.
Sure, there’s still more to learn (there always is!), but you’ve got the confidence and skills to keep going. Don’t stop here—keep experimenting, keep breaking things (on purpose!), and keep growing. The terminal isn’t scary anymore—it’s yours to command.
So... what will you automate first? Whatever it is, you’ve got this. Happy scripting—and remember, every pro started exactly where you did: at the beginning.
IF YOU FIND THIS ARTICLE HELPFULL CONSIDER SUPPORTING US
A WEBSITE TEMPLATE FOR JUST 1$ CHECK THIS OUT
hello fuck you bitches
ReplyDeletefuck fuck fuck why the fuck does coments are not removes
Delete