All Cheat SheetsBash
Bash Scripting & CLI One-Liners Cheat Sheet
Variables, parameter expansion, condition tests, loops, redirection, and text processing pipelines
Script Template & Safe Header
Best practice strict mode flags for robust shell scripts
Strict Bash HeaderExit on error (-e), unset variables (-u), and pipeline fails (-o pipefail)
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'Check command exit status
if [ $? -ne 0 ]; then
echo "Command failed" >&2
exit 1
fiParameter Expansion & String Operations
Default value if unsetUses default without modifying VAR
${VAR:-default_value}String lengthNumber of characters in variable
${#VAR}Substring extractionFirst 5 characters (offset:length)
${VAR:0:5}Strip prefix patternShortest vs longest match from start
${FILE#*.}
${FILE##*.}Strip suffix patternShortest vs longest match from end
${FILE%.*}
${FILE%%.*}Search and replaceFirst match vs all matches
${VAR/old/new}
${VAR//old/new}Condition Tests & Logic
Check if file exists
if [[ -f "$FILE" ]]; then ... fiCheck if directory exists
if [[ -d "$DIR" ]]; then ... fiCheck if string is non-empty
if [[ -n "$VAR" ]]; then ... fiCheck if command exists in PATH
if command -v git &>/dev/null; then ... fiLoops & Redirection
Loop over files safely
for f in *.json; do
[ -e "$f" ] || continue
echo "Processing $f"
doneRead file line by line
while IFS= read -r line; do
echo "$line"
done < input.txtRedirect stdout and stderrCapture both stdout & stderr to file
command > output.log 2>&1
command &> output.log