Bash - Bourne Again Shell
2 min readArticle
Bash is the default shell on most Linux systems and macOS (pre-Catalina). It's the scripting language you'll spend the most time with in security work — automating scans, writing exploit chains, processing tool output, managing files, and building quick-and-dirty tools.
Shebang and Basics
bash
#!/bin/bash
# This is a comment
# Variables
TARGET="192.168.1.1"
PORT=443
# Echo with quotes (preserve spacing)
echo "Scanning $TARGET on port $PORT"
# Command substitution
CURRENT_USER=$(whoami)
IP_ADDR=$(hostname -I | awk '{print $1}')
Control Flow
bash
# If/else
if [ "$1" == "" ]; then
echo "Usage: $0 <target>"
exit 1
fi
# If with command result
if ping -c 1 192.168.1.1 &>/dev/null; then
echo "Host is up"
else
echo "Host is down"
fi
# For loop
for ip in 192.168.1.{1..254}; do
ping -c 1 -W 1 $ip &>/dev/null && echo "$ip is up"
done
# While loop
while read line; do
echo "Processing: $line"
done < input.txt
Functions
bash
scan_port() {
local host=$1
local port=$2
timeout 1 bash -c "echo >/dev/tcp/$host/$port" 2>/dev/null && echo "$port open"
}
# Quick port scanner in pure bash
for port in 22 80 443 3389 8080; do
scan_port 192.168.1.1 $port
done
File Operations
bash
# Check if file exists
[ -f /etc/passwd ] && echo "File exists"
# Check if directory exists
[ -d /tmp/loot ] || mkdir -p /tmp/loot
# Read file line by line
while IFS= read -r line; do
echo "$line"
done < wordlist.txt
# Append to file
echo "result" >> output.txt
# Write file
cat > /tmp/script.sh << 'EOF'
#!/bin/bash
whoami
EOF
Useful One-Liners for Security
bash
# Ping sweep
for i in {1..254}; do ping -c1 -W1 192.168.1.$i &>/dev/null && echo "192.168.1.$i up" & done; wait
# Port scan
for p in {1..1024}; do timeout 0.5 bash -c "echo >/dev/tcp/192.168.1.1/$p" 2>/dev/null && echo "$p open"; done
# Extract IPs from file
grep -oP '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}' file.txt | sort -u
# Watch a log file for specific string
tail -f /var/log/auth.log | grep --line-buffered "Failed"
# Kill process by name
pkill -f "airmon-ng"
# Run command on multiple hosts
for host in 10.0.0.{1..10}; do ssh $host "uname -a"; done
Argument Parsing
bash
#!/bin/bash
while [[ $# -gt 0 ]]; do
case $1 in
-t|--target)
TARGET="$2"
shift 2
;;
-p|--port)
PORT="$2"
shift 2
;;
-h|--help)
echo "Usage: $0 -t TARGET -p PORT"
exit 0
;;
*)
echo "Unknown option: $1"
exit 1
;;
esac
done
Tips
- Always quote variables:
"$var"not$var(handles spaces) - Use
set -eto exit on error,set -xto debug $?is the exit code of the last command2>/dev/nullsuppresses stderr&>/dev/nullsuppresses both stdout and stderr
See Also
- windows-batch-scripting-guide - Windows equivalent
- powershell-scripting-guide - More powerful Windows scripting
techzonesite.comUnlock Your IT Potential