Why Shell Scripts Are a Security Risk
Shell scripts run with the permissions of whoever calls them, inherit environment variables
from the caller, and parse input in ways that invite injection. Before writing another
#!/bin/bash script that runs as root, let me show you how I write them safely.
Strict Mode First
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -e— exit on errorset -u— error on undefined variablesset -o pipefail— catch failures inside pipes
Safe Temporary Files
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT
Never use predictable paths like /tmp/myscript.tmp. Race conditions in /tmp are a
classic privilege escalation vector.
Input Validation
validate_ip() {
local ip="$1"
if [[ ! "$ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then
echo "ERROR: Invalid IP: $ip" >&2
exit 1
fi
}
Avoid eval and Unsafe Constructs
# BAD — command injection if USER_INPUT contains shell metacharacters
eval "grep $USER_INPUT /var/log/auth.log"
# GOOD
grep -- "$USER_INPUT" /var/log/auth.log
Logging
log() { echo "[$(date -Iseconds)] $*" | tee -a /var/log/myscript.log; }
log "Starting backup for host: $HOST"
Defensive Takeaways
- Always use
set -euo pipefail— it is not optional for scripts with side effects - Quote every variable —
"$VAR"not$VAR - Scripts that run as root should validate every external input before acting
- Prefer Python for complex logic — bash is not the right tool for anything with parsing
Keep going
Get the next writeup in your inbox
New posts delivered when I publish. No spam.