Bash Scripting Basics: Automate Tasks Like a Pro
Learn Bash scripting from scratch covering variables, conditionals, loops, functions, error handling, and practical automation scripts for cybersecurity.
Why Learn Bash Scripting?
Bash scripting automates repetitive tasks on Linux. Instead of typing commands manually, scripts execute sequences automatically. For cybersecurity, Bash scripting automates reconnaissance, log analysis, tool execution, and reporting.
Prerequisites
Basic Linux commands (ls,cd, grep, awk, sed), terminal navigation, and a text editor.
Script Structure
Every script starts with a shebang and can include comments:
#!/bin/bash
# This is a comment
echo "Hello, World!"
Making Scripts Executable
chmod +x script.sh
./script.sh
Variables
#!/bin/bash
name="KaliGo"
echo "Hello, $name!"
current_date=$(date)
echo "Today is: $current_date"
count=$((5 * 10))
echo "Result: $count"
Arrays
tools=("nmap" "wireshark" "metasploit")
echo ${tools[0]} # nmap
echo ${tools[@]} # All elements
echo ${#tools[@]} # Array length
User Input
read -p "Enter target IP: " target
echo "Scanning $target..."
read -s -p "Enter password: " password
Conditionals
if [ "$num" -gt 10 ]; then
echo "Greater than 10"
elif [ "$num" -eq 10 ]; then
echo "Exactly 10"
else
echo "Less than 10"
fi
File Tests
if [ -f "$file" ]; then echo "File exists"; fi
if [ -d "$dir" ]; then echo "Directory exists"; fi
if [ -x "$file" ]; then echo "File is executable"; fi
Loops
# For loop
for tool in nmap wireshark metasploit; do
echo "Tool: $tool"
done
# Number range
for i in {1..5}; do
echo "Iteration: $i"
done
# While loop
count=1
while [ "$count" -le 5 ]; do
echo "Count: $count"
((count++))
done
# Read file line by line
while IFS= read -r line; do
echo "Line: $line"
done < targets.txt
Functions
scan_port() {
local host=$1
local port=$2
nc -zv "$host" "$port" 2>/dev/null
if [ $? -eq 0 ]; then
echo "Port $port is OPEN on $host"
else
echo "Port $port is CLOSED on $host"
fi
}
scan_port "192.168.1.1" 80
Error Handling
set -euo pipefail # Exit on error, undefined vars, pipe failures
Practical Automation
Network Scan Script
#!/bin/bash
set -euo pipefail
TARGET="$1"
OUTPUT_DIR="scan_results"
mkdir -p "$OUTPUT_DIR"
nmap -sn "$TARGET" -oG "$OUTPUT_DIR/ping_scan.txt"
nmap -sV -sC "$TARGET" -oN "$OUTPUT_DIR/port_scan.txt"
nmap --script vuln "$TARGET" -oN "$OUTPUT_DIR/vuln_scan.txt"
echo "Scan complete. Check $OUTPUT_DIR."
Log Analysis Script
#!/bin/bash
LOG_FILE="/var/log/auth.log"
echo "=== SSH Failed Logins ==="
grep "Failed password" "$LOG_FILE" | awk '{print $1, $2, $11}' | sort | uniq -c | sort -rn | head -10
Real-World Examples
Automated reconnaissance running theHarvester, DNS enumeration, and Nmap. Backup automation with cron. Phishing URL checker against multiple APIs.
Common Mistakes
Missing shebang, spaces in variable assignment (name = "value" is wrong), not quoting variables, not checking exit codes.
Best Practices
Use set -euo pipefail. Quote all variable expansions. Use meaningful names. Validate input. Handle errors gracefully. Use trap for cleanup. Lint with shellcheck.
Related Tools
shellcheck — Static analysis. bashdb — Debugger. shfmt — Formatter. expect — Interactive automation. parallel — Execute in parallel.
Related Articles
Summary
Bash scripting automates tasks using variables, conditionals, loops, functions, and error handling. Key practices: shebang line, proper quoting, exit codes ($?), and set -euo pipefail. Practical uses include automated scanning, log analysis, and tool orchestration.
Knowledge Check
#!/bin/bash do?set -euo pipefail do?$? in a Bash script?Frequently Asked Questions
Continue Learning
Linux Terminal Guide: Advanced Shell Skills for Professionals
Advanced Linux terminal techniques including shell customization, multiplexing, productivity tools, and scripting best practices.
Linux · BeginnerCommand Line Essentials: Mastering the Terminal for Security Work
Essential command line skills for cybersecurity professionals including navigation, text processing, scripting, and automation.
Linux · BeginnerLinux Process Management: Monitoring and Controlling Processes
Learn to manage Linux processes effectively including monitoring tools, signals, priority control, background jobs, and automation with systemd.
Linux · Beginner100 Essential Linux Commands Every Beginner Should Know
A quick-reference cheat sheet of 100 essential Linux commands every beginner should know, organized by category with syntax, examples, and practical use cases for system administration and cybersecurity.
Related Security Tools
SMBClient
Learn how to use SMBClient on Kali Linux: install Samba's FTP-like SMB/CIFS client, list shares, connect as a guest or with credentials, browse folders, and upload or download files on Windows, Samba, or NAS devices. For authorized assessments, check ports 139/445 with Nmap before testing share permissions.
Reverse EngineeringADB
ADB, or Android Debug Bridge, is a versatile command-line tool that acts as a client-server program, facilitating communication between your development machine (the client) and an Android device (running the adbd daemon) via a server process binding TCP port 5037. It ships as part of the Android SDK Platform Tools, and on Kali Linux, it's available as the `android-tools-adb` package. ADB is the standard device bridge for Android mobile pentesting and forensics, enabling actions like deploying Frida servers, pulling APKs, and capturing detailed logcat output for analysis.
Web ApplicationCommix
Commix (Command Injection Exploiter) is an automated tool designed to test, detect, and exploit command injection vulnerabilities in web applications, facilitating automated OS shell access.
Reverse EngineeringGDB
Learn how to use GDB, the GNU Debugger, by building a small C program with debug symbols and following it from the first breakpoint to a crash. Use the same steps to inspect variables, read a backtrace, and tell when a core dump or a look at the assembly would help.