← All Tools

💻 Bash Scripting Cheat Sheet

87+ examples • Variables, loops, functions • Best practices

Variables & Data Types 12String Operations 10Conditionals 7Loops 9Functions 6Input & Output 9Arithmetic 5Process & Job Control 9Text Processing 12Script Best Practices 8

Variables & Data Types 12

Variable assignment and usage
name="Alice"
echo "Hello $name"
Read-only constant
readonly PI=3.14159
Delete a variable
unset myvar
Default value if unset
echo "${name:-default}"
Assign default if unset
echo "${name:=default}"
Alt value if set
echo "${name:+alt}"
String length
echo "${#name}"
Array basics
arr=(one two three)
echo "${arr[1]}"  # two
Array operations
echo "${arr[@]}"  # all elements
echo "${#arr[@]}" # array length
Append to array
arr+=(four five)
Associative array (dict)
declare -A map
map[name]="Alice"
map[age]=30
echo "${map[name]}"
Integer variable
declare -i num=42

String Operations 10

To uppercase
echo "${str^^}"  # UPPERCASE
To lowercase
echo "${str,,}"  # lowercase
Substring
echo "${str:0:5}"  # first 5 chars
Remove shortest prefix
echo "${str#*.}"  # remove prefix
Remove longest prefix (get extension)
echo "${str##*.}" # remove all prefix
Remove shortest suffix
echo "${str%/*}"  # remove suffix
Replace first occurrence
echo "${str/old/new}"  # first match
Replace all occurrences
echo "${str//old/new}" # all matches
Check if contains substring
if [[ "$str" == *"pattern"* ]]; then
  echo "contains"
fi
Regex match
[[ "$str" =~ ^[0-9]+$ ]] && echo "numeric"

Conditionals 7

If/elif/else
if [[ $x -gt 10 ]]; then
  echo "big"
elif [[ $x -gt 5 ]]; then
  echo "medium"
else
  echo "small"
fi
File test operators
[[ -f "file.txt" ]]  # file exists
[[ -d "dir" ]]      # directory exists
[[ -r "file" ]]     # readable
[[ -w "file" ]]     # writable
[[ -x "file" ]]     # executable
[[ -s "file" ]]     # non-empty
String comparisons
[[ "$a" == "$b" ]]   # string equal
[[ "$a" != "$b" ]]   # string not equal
[[ -z "$str" ]]      # string is empty
[[ -n "$str" ]]      # string not empty
Numeric comparisons
[[ $a -eq $b ]]  # equal
[[ $a -ne $b ]]  # not equal
[[ $a -lt $b ]]  # less than
[[ $a -gt $b ]]  # greater than
[[ $a -le $b ]]  # less or equal
[[ $a -ge $b ]]  # greater or equal
AND condition
[[ $a -gt 0 && $a -lt 100 ]]
OR condition
[[ $a -eq 0 || $a -eq 1 ]]
Case statement
case "$fruit" in
  apple)  echo "red"  ;;
  banana) echo "yellow" ;;
  *)      echo "unknown" ;;
esac

Loops 9

For loop (list)
for i in 1 2 3 4 5; do
  echo "$i"
done
For loop (range)
for i in {1..10}; do echo "$i"; done
For loop (range with step)
for i in {0..100..5}; do echo "$i"; done
C-style for loop
for ((i=0; i<10; i++)); do
  echo "$i"
done
Loop over files
for file in *.txt; do
  echo "$file"
done
While loop
while [[ $count -lt 10 ]]; do
  ((count++))
done
Read file line by line
while IFS= read -r line; do
  echo "$line"
done < file.txt
Until loop
until [[ $status == "ready" ]]; do
  sleep 1
  status=$(check_status)
done
Break and continue
for i in {1..10}; do
  [[ $i -eq 5 ]] && continue
  [[ $i -eq 8 ]] && break
  echo "$i"
done

Functions 6

Basic function
greet() {
  echo "Hello, $1!"
}
greet "Alice"
Return value via echo
add() {
  local result=$(( $1 + $2 ))
  echo $result
}
sum=$(add 3 5)  # 8
Local variables & defaults
process() {
  local name="$1"
  local -i count="${2:-1}"
  echo "$name x $count"
}
Trap on exit (cleanup)
cleanup() {
  rm -f /tmp/myapp_*
  echo "Cleaned up"
}
trap cleanup EXIT
Trap signals
trap "echo Interrupted; exit 1" INT TERM
Error/die function
die() {
  echo "ERROR: $*" >&2
  exit 1
}
[[ -f config ]] || die "No config file"

Input & Output 9

Read user input
read -p "Enter name: " name
Read secret input
read -sp "Password: " pass
Read with timeout
read -t 5 -p "Quick! " answer
Redirect output
echo "hello" > file.txt   # overwrite
echo "world" >> file.txt  # append
Redirect stderr
cmd 2>/dev/null           # hide errors
cmd &>/dev/null           # hide all output
cmd 2>&1                  # stderr to stdout
Command substitution
result=$(command)
Pipe to bc (math)
echo "scale=2; 22/7" | bc
Here document
cat <<EOF
Hello $name
Today is $(date)
EOF
Formatted output
printf "%-10s %5d\n" "$name" "$age"

Arithmetic 5

Basic arithmetic
echo $(( 5 + 3 ))    # 8
echo $(( 10 % 3 ))   # 1
echo $(( 2 ** 10 ))  # 1024
Increment/compound assignment
((count++))
((total += price))
Arithmetic in conditions
if (( x > 10 )); then echo "big"; fi
Floating point with bc
echo "scale=4; 22/7" | bc   # 3.1428
Floating point with awk
awk "BEGIN {printf \"%.2f\", 22/7}"  # 3.14

Process & Job Control 9

Run in background
command &
Run parallel, wait for all
command1 & command2 & wait
List background jobs
jobs
Bring job to foreground
fg %1
Survive terminal close
nohup command &
Special variables
$$   # current PID
$!   # last background PID
$?   # last exit code
Run if previous succeeded
command1 && command2
Run if previous failed
command1 || command2
Subshell (doesn't affect parent)
(cd /tmp && do_something)

Text Processing 12

Search for pattern
grep "pattern" file.txt
Recursive search
grep -r "TODO" --include="*.py" .
Count matches
grep -c "error" log.txt
Replace all in file
sed 's/old/new/g' file.txt
Replace in-place
sed -i 's/old/new/g' file.txt
Print lines 5-10
sed -n '5,10p' file.txt
Print columns 1 and 3
awk '{print $1, $3}' file.txt
Custom delimiter
awk -F: '{print $1}' /etc/passwd
Frequency count
sort file.txt | uniq -c | sort -rn
Extract CSV columns
cut -d"," -f1,3 data.csv
Translate characters
tr "a-z" "A-Z" < file.txt
Count lines
wc -l file.txt

Script Best Practices 8

Strict mode (recommended!)
#!/usr/bin/env bash
set -euo pipefail
Set options explained
set -e   # exit on error
set -u   # error on unset vars
set -o pipefail  # catch pipe errors
set -x   # debug (print commands)
Logging function
log() {
  echo "[$(date +%Y-%m-%dT%H:%M:%S)] $*"
}
Get script directory
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
Argument validation
[[ $# -lt 2 ]] && { echo "Usage: $0 <src> <dst>"; exit 1; }
Safe temp files
tmpfile=$(mktemp)
trap "rm -f $tmpfile" EXIT
Check dependency exists
if ! command -v jq &>/dev/null; then
  echo "jq required"
  exit 1
fi
Parse command-line options
# getopts for flags
while getopts "vf:o:" opt; do
  case $opt in
    v) VERBOSE=1 ;;
    f) FILE="$OPTARG" ;;
    o) OUTPUT="$OPTARG" ;;
    ?) exit 1 ;;
  esac
done

Made with ♥ by Kas Developer Tools

\xF0\x9F\x92\x99 Tip\xF0\x9F\x93\x9A Get Bundle \x244.99