Shell Script Cheatsheet
Quick reference for Bash/POSIX syntax used in deploy, build, and automation scripts on Linux. For basics, see The Unix Shell.
Safe Script Header (Strict Mode)
#!/usr/bin/env bash
set -euo pipefail
# -e: exit immediately on error
# -u: treat unset variables as errors
# -o pipefail: fail a pipeline if any command in it fails
Variables, Arguments & Parameter Expansion
NAME="chipfc"
echo "Hello $NAME"
# Script arguments
# $0: script name | $1, $2: args | $#: arg count | "$@": all args
VAR="${1:-default_val}" # Default value if $1 is empty or unset
: "${API_URL:?Missing API_URL}" # Fail with message if unset
FILE="/path/to/archive.tar.gz"
echo "${FILE##*/}" # archive.tar.gz (basename)
echo "${FILE%/*}" # /path/to (dirname)
echo "${FILE%.gz}" # /path/to/archive.tar (strip suffix)
Conditionals (if / [[ ... ]])
if [[ -f "$FILE" ]]; then
echo "File exists"
elif [[ -d "$DIR" ]]; then
echo "Directory exists"
else
echo "Not found"
fi
| Test | Meaning |
|---|---|
-f "$p" / -d "$p" / -e "$p" | Regular file / Directory / Exists |
-z "$s" / -n "$s" | Empty string / Non-empty string |
"$a" == "$b" / "$a" != "$b" | String comparison |
$x -eq $y / -ne / -lt / -gt | Integer comparison |
Loops & Functions
for file in *.md; do
echo "Processing $file"
done
while IFS= read -r line; do
echo "$line"
done < input.txt
log_info() {
local msg="$1"
echo "[INFO] $msg"
}
Cleanup with trap
TMP_DIR="$(mktemp -d)"
cleanup() {
rm -rf "$TMP_DIR"
}
trap cleanup EXIT
Checking & Debugging Scripts
shellcheck deploy.sh # Catch quoting, variable, and common shell bugs
bash -n deploy.sh # Syntax check without executing
bash -x deploy.sh # Trace each command as it runs
References
- GNU Bash Manual
- ShellCheck — Static analysis tool for shell scripts.
- Pure Bash Bible — Collection of pure Bash idioms.
- Google Shell Style Guide