Advanced Shell Scripting
Functions, arrays, and error handling. Build production-grade security tools.
Functions
Functions make scripts modular, reusable, and maintainable. Define once, call anywhere.
# Define a function
scan_host() {
local host=$1
echo "Scanning $host..."
for port in 22 80 443; do
nc -z -w1 $host $port 2>/dev/null && \
echo " [OPEN] $port"
done
}
# Call the function
scan_host "192.168.1.1"
scan_host "192.168.1.2"
Arrays
# Declare an array
targets=("192.168.1.1" "192.168.1.2" "192.168.1.3")
# Loop through array
for ip in "${targets[@]}"; do
scan_host "$ip"
done
# Array length: ${#targets[@]}
# Single element: ${targets[0]}
Error Handling
set -e
Exit immediately if any command fails. Prevents cascading errors.
set -u
Treat unset variables as errors. Catches typos in variable names.
trap
Catch signals and cleanup. trap cleanup EXIT
#!/bin/bash
set -euo pipefail # Strict mode
cleanup() {
echo "Cleaning up temp files..."
rm -f /tmp/scan_*.tmp
}
trap cleanup EXIT
# Script continues...
LAB: Function Playground
Build a multi-target scanner using functions and arrays. Your script should scan multiple hosts!
Define a function
Create an array of targets
Loop through the array
Call your function for each target
scanner.sh
⬤Output
Ready to run your script...
Build a scanner that:
1. Defines a scan_target() function
2. Creates a targets=() array
3. Loops through with for...in
4. Calls scan_target for each