Bash Scripting Cheat Sheet - CodeSwordsman

Bash scripting essentials: variables and parameter expansion, conditionals, loops, functions and arrays, robust set -euo pipefail and trap patterns, plus awk, sed and getopts recipes.

Bash 5.xUpdated 2026-10-3021 commands

Variables & Arguments

Use env to locate bash, then fail fast on errors, unset vars and pipeline failures

#!/usr/bin/env bash
set -euo pipefail

No spaces around =, and brace variable references to avoid ambiguous names

APP_ENV="prod"
echo "deploy to ${APP_ENV}"

:- supplies a default, :? aborts with a message for required values

PORT="${PORT:-8080}"
NAME="${NAME:?NAME is required}"

$# counts args, $1 is the first; always loop with "$@" to keep spaces intact

echo "args=$# first=$1 all=$*"
for arg in "$@"; do echo "$arg"; done

Use $( ) for command substitution; it nests and reads better than backticks

NOW=$(date +%F)
FILES=$(ls *.log | wc -l)

Conditionals & Loops

[[ ]] supports && and patterns and is safer than [ ] for file tests

if [[ -f "$CONF" && -r "$CONF" ]]; then
  echo "readable"
else
  echo "missing" >&2
  exit 1
fi

Multi-branch dispatch for subcommands; ;; acts as break

case "$1" in
  start) echo start ;;
  stop) echo stop ;;
  *) echo "usage: $0 start|stop" ;;
esac

Globs stay literal when unmatched, so check existence inside the loop

for f in /var/log/*.log; do
  [[ -e "$f" ]] || continue
  echo "$f"
done

Read line by line; IFS= and -r preserve whitespace and backslashes

while IFS= read -r line; do
  echo "$line"
done < hosts.txt

C-style for loops and arithmetic expansion with (( ))

for ((i = 0; i < 3; i++)); do echo "$i"; done
((count++))

Functions & Arrays

Declare locals inside functions to avoid leaking into the global scope

log() {
  local level="$1"
  shift
  echo "[$level] $*" >&2
}
log INFO "started"

Index and count array items; quote expansions when looping

hosts=(web1 web2 web3)
echo "${hosts[0]} ${#hosts[@]}"
for h in "${hosts[@]}"; do echo "$h"; done

Associative arrays need Bash 4 or newer

declare -A ports=([web]=80 [api]=8080)
echo "${ports[api]}"
for k in "${!ports[@]}"; do echo "$k=${ports[$k]}"; done

Robustness

Exit on error, fail on unset vars and propagate pipeline failures

set -euo pipefail

Behavior shifts inside if conditions and substitutions; mind exit code checks.

Clean up temp resources on both normal exit and interruption

cleanup() {
  rm -rf "$TMP_DIR"
}
trap cleanup EXIT

[[ ]] for strings and globs, [ ] with -gt and -lt for numeric tests

[[ "$name" == *.log ]]
[ "$count" -gt 10 ]

Static checks for unquoted variables and invalid tests; worth running in CI

shellcheck deploy.sh

Text Processing & Options

grep counts matches, awk extracts fields; the most common log analysis combo

grep -c "ERROR" app.log
awk '{print $1, $4}' access.log | head

In-place replace with a .bak copy so a bad edit can be reverted

sed -i.bak 's/localhost/127.0.0.1/g' app.conf

Top-10 frequency pipeline for busiest IPs or endpoints

sort access.log | uniq -c | sort -rn | head -10

Parse short flags like -e prod -p 8080 in small to medium scripts

while getopts ":e:p:" opt; do
  case "$opt" in
    e) ENV="$OPTARG" ;;
    p) PORT="$OPTARG" ;;
    *) exit 2 ;;
  esac
done

This website uses cookies to ensure you get the best experience on our website. Privacy Policy.