Code BeautifierDev Tools

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
fi

Parameter 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 ... fi
Check if directory exists
if [[ -d "$DIR" ]]; then ... fi
Check if string is non-empty
if [[ -n "$VAR" ]]; then ... fi
Check if command exists in PATH
if command -v git &>/dev/null; then ... fi

Loops & Redirection

Loop over files safely
for f in *.json; do
  [ -e "$f" ] || continue
  echo "Processing $f"
done
Read file line by line
while IFS= read -r line; do
  echo "$line"
done < input.txt
Redirect stdout and stderrCapture both stdout & stderr to file
command > output.log 2>&1
command &> output.log

Try Related In-Browser Tools