DevOpsil
Bash40 commands

Bash Scripting Cheat Sheet

Essential Bash scripting patterns — variables, conditionals, loops, functions, string manipulation, and error handling.

Variables & Strings

CommandDescription
VAR="hello"
Assign variable (no spaces around =)
echo "${VAR}"
Use variable in string
${VAR:-default}
Default value if unset
${#VAR}
String length
${VAR^^}
Uppercase
${VAR,,}
Lowercase
${VAR/old/new}
Replace first occurrence
${VAR//old/new}
Replace all occurrences
$(command)
Command substitution
readonly PI=3.14
Declare constant

Conditionals

CommandDescription
if [[ -f file ]]; then ...; fi
Check if file exists
if [[ -d dir ]]; then ...; fi
Check if directory exists
if [[ -z "$VAR" ]]; then ...; fi
Check if string is empty
if [[ -n "$VAR" ]]; then ...; fi
Check if string is not empty
if [[ "$A" == "$B" ]]; then ...; fi
String equality
if [[ $NUM -gt 10 ]]; then ...; fi
Numeric comparison
if command; then ...; fi
Check command exit status
[[ -f f ]] && echo "exists" || echo "no"
Ternary-style one-liner

Loops

CommandDescription
for f in *.txt; do echo "$f"; done
Loop over files
for i in {1..10}; do echo $i; done
Loop over range
while read -r line; do echo "$line"; done < file
Read file line by line
while true; do ...; sleep 5; done
Infinite loop with delay
for arg in "$@"; do echo "$arg"; done
Loop over script arguments

Functions

CommandDescription
my_func() { echo "Hello $1"; }
Define function
local result="value"
Local variable in function
return 0
Return exit code from function
result=$(my_func "arg")
Capture function output

Error Handling

CommandDescription
set -e
Exit on first error
set -u
Error on undefined variables
set -o pipefail
Catch errors in pipes
set -euo pipefail
Strict mode (combine all three)
trap 'cleanup' EXIT
Run cleanup on exit
command || { echo "failed"; exit 1; }
Handle command failure

Arrays & I/O

CommandDescription
arr=(one two three)
Declare array
${arr[0]}
Access first element
${arr[@]}
All elements
${#arr[@]}
Array length
read -p "Enter name: " name
Prompt for input
command > out.log 2>&1
Redirect stdout and stderr
command 2>/dev/null
Suppress error output