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.