On this page

Bash Cheat Sheet

Quick reference for Bash variables, arrays, string manipulation, conditionals, loops, file operations, text processing, and common one-liners.


Variables

# Assignment (no spaces around =)
name="Alice"
count=42
readonly PI=3.14              # Cannot be reassigned

# Usage
echo "$name"                  # Quoted (preferred)
echo "${name}_suffix"         # With braces for clarity

# Default values
${var:-default}               # Use default if unset/empty
${var:=default}               # Set and use default if unset/empty
${var:+alt}                   # Use alt if var is set AND non-empty
${var:?error msg}             # Error if unset/empty
${var-default}                # Without the colon: only if unset (empty counts as set)

# Command substitution
now=$(date +%Y-%m-%d)
files=$(ls *.txt)             # fragile with spaces; prefer files=(*.txt)
content=$(< file.txt)         # Read a file without spawning cat

# Arithmetic (integers only; use bc or awk for floats)
result=$((5 + 3))
((count++))
((total = a + b * c))
echo $(( 2**10 )) $(( 17 % 5 )) $(( 0xff ))   # 1024 2 255

# printf (more portable and predictable than echo)
printf '%s=%d\n' "$name" "$count"
printf -v padded '%05d' 42    # Assign to a variable: 00042

# Inspect / debug
declare -p name               # Show a variable's type and value
echo "${name@Q}"              # Shell-quoted value (Bash 4.4+)

Special Variables

VariableDescription
$0Script name
$1 - $9Positional arguments
$#Number of arguments
$@All arguments; "$@" keeps each one a separate word
$*All arguments; "$*" joins them into one string (with the first char of IFS)
${10}Positional args past 9 need braces
$?Exit status of last command
$$Current shell PID
$!PID of last background process
$_Last argument of previous command
${PIPESTATUS[@]}Exit status of every command in the last pipeline
$BASH_SOURCE / $LINENO / $FUNCNAMECurrent file, line, function (for error messages)
$RANDOMRandom integer 0-32767
$SECONDSSeconds since the shell started
$EPOCHSECONDSUnix time (Bash 5.0+)
$BASH_VERSIONBash version (macOS still ships 3.2 as /bin/bash)

Arrays

# Indexed arrays
arr=(apple banana cherry)
arr[3]="date"
echo "${arr[0]}"              # apple
echo "${arr[@]}"              # All elements
echo "${#arr[@]}"             # Length: 4
echo "${arr[@]:1:2}"          # Slice: banana cherry

# Append
arr+=("elderberry")

# Iterate
for item in "${arr[@]}"; do
    echo "$item"
done

# Associative arrays (Bash 4+)
declare -A colors
colors[red]="#FF0000"
colors[green]="#00FF00"
echo "${colors[red]}"
echo "${!colors[@]}"          # All keys
[[ -v colors[blue] ]] || echo "no blue"   # Key exists? (Bash 4.3+)
unset 'colors[red]'           # Delete a key

# Read lines into an array (Bash 4+)
mapfile -t lines < file.txt   # same as readarray
mapfile -t logs < <(find . -name '*.log')

# Split a string into an array
IFS=, read -ra parts <<< "a,b,c"

# Glob into an array (safe with spaces)
files=(*.txt)

# Delete an element / whole array
unset 'arr[1]'
unset arr

String Manipulation

str="Hello, World!"

# Length
echo "${#str}"                # 13

# Substring
echo "${str:7}"               # World!
echo "${str:7:5}"             # World

# Replacement
echo "${str/World/Bash}"      # Hello, Bash! (first match)
echo "${str//l/L}"            # HeLLo, WorLd! (all matches)

# Removal (pattern)
file="archive.tar.gz"
echo "${file#*.}"             # tar.gz (remove shortest from start)
echo "${file##*.}"            # gz (remove longest from start)
echo "${file%.*}"             # archive.tar (remove shortest from end)
echo "${file%%.*}"            # archive (remove longest from end)

# Case conversion (Bash 4+)
echo "${str^^}"               # HELLO, WORLD! (uppercase)
echo "${str,,}"               # hello, world! (lowercase)
echo "${str^}"                # Hello, World! (capitalize first)

# Path helpers without dirname/basename
path="/var/log/app/error.log"
echo "${path##*/}"            # error.log  (basename)
echo "${path%/*}"             # /var/log/app (dirname)

# Trim leading/trailing whitespace
s="  hi  "
s="${s#"${s%%[![:space:]]*}"}"; s="${s%"${s##*[![:space:]]}"}"

# Indirect expansion
key="HOME"; echo "${!key}"    # value of $HOME

Brace Expansion & Globbing

mkdir -p src/{api,web,shared}       # 3 dirs
cp config.yml{,.bak}                # config.yml -> config.yml.bak
echo file{1..3}.txt                 # file1.txt file2.txt file3.txt

shopt -s nullglob     # unmatched glob expands to nothing (not the literal pattern)
shopt -s globstar     # ** matches recursively: for f in **/*.md
shopt -s extglob      # !(*.log), +(a|b), @(x|y)
shopt -s dotglob      # globs include dotfiles

Conditionals

test / [ ] / [[ ]]

# Prefer [[ ]] over [ ] -- safer, more features
if [[ "$name" == "Alice" ]]; then
    echo "Hi Alice"
elif [[ "$name" == "Bob" ]]; then
    echo "Hi Bob"
else
    echo "Who are you?"
fi

String Comparisons

OperatorDescription
==Equal
!=Not equal
<Less than (lexicographic)
>Greater than (lexicographic)
-z "$str"String is empty
-n "$str"String is not empty
=~Regex match (inside [[ ]]); captures land in BASH_REMATCH
== a*Glob match (inside [[ ]], pattern unquoted)
if [[ $version =~ ^v([0-9]+)\.([0-9]+) ]]; then
    major=${BASH_REMATCH[1]} minor=${BASH_REMATCH[2]}
fi
[[ $file == *.tar.gz ]] && echo "tarball"

Do not quote the regex on the right of =~; quoting makes it a literal string. Store complex regexes in a variable: re='^[0-9]+$'; [[ $x =~ $re ]].

Integer Comparisons

OperatorDescription
-eqEqual
-neNot equal
-ltLess than
-leLess than or equal
-gtGreater than
-geGreater than or equal

File Tests

OperatorDescription
-f fileRegular file exists
-d dirDirectory exists
-e pathPath exists (any type)
-r fileFile is readable
-w fileFile is writable
-x fileFile is executable
-s fileFile is non-empty
-L fileFile is symlink
-v varVariable is set (Bash 4.2+)
-t 1stdout is a terminal (decide whether to print colours)
f1 -nt f2f1 is newer than f2
f1 -ot f2f1 is older than f2

Logical Operators

# Inside [[ ]]
[[ $a == 1 && $b == 2 ]]     # AND
[[ $a == 1 || $b == 2 ]]     # OR
[[ ! -f file ]]              # NOT

# Integer tests read better in (( ))
(( count > 10 )) && echo "big"

# Command chaining
mkdir -p out && cd out       # run second only if first succeeds
cd /missing || exit 1        # run second only if first fails

Loops

# for loop
for i in 1 2 3 4 5; do
    echo "$i"
done

# C-style for
for ((i = 0; i < 10; i++)); do
    echo "$i"
done

# Range
for i in {1..10}; do echo "$i"; done
for i in {0..100..5}; do echo "$i"; done  # Step by 5

# while loop
while [[ $count -lt 10 ]]; do
    ((count++))
done

# Read lines from file
while IFS= read -r line; do
    echo "$line"
done < file.txt

# Read lines from command
while IFS= read -r line; do
    echo "$line"
done < <(find . -name "*.log")

# Filenames with any characters (spaces, newlines)
while IFS= read -r -d '' f; do
    echo "$f"
done < <(find . -name "*.log" -print0)

# Read CSV fields
while IFS=, read -r name age city; do
    echo "$name is $age"
done < people.csv

# Iterate over files (no ls parsing)
for f in ./*.txt; do
    [[ -e $f ]] || continue   # skip if glob matched nothing
    echo "$f"
done

# Prompt the user
read -rp "Continue? [y/N] " answer
read -rsp "Password: " pw; echo   # -s hides input
read -t 5 -rp "5s timeout: " x    # -t timeout

# Infinite loop
while true; do
    check_status || break
    sleep 5
done

# until loop
until [[ $status == "ready" ]]; do
    status=$(get_status)
    sleep 1
done

Case Statement

case "$action" in
    start)
        start_service
        ;;
    stop|kill)
        stop_service
        ;;
    restart)
        stop_service
        start_service
        ;;
    *)
        echo "Usage: $0 {start|stop|restart}"
        exit 1
        ;;
esac

Functions

# Function definition
greet() {
    local name="$1"           # Local variable
    local greeting="${2:-Hello}"
    echo "${greeting}, ${name}!"
    return 0                  # Exit status
}

# Call
greet "Alice"                 # Hello, Alice!
greet "Bob" "Hey"             # Hey, Bob!

# Capture output
result=$(greet "Alice")

# Return values via exit status
is_even() {
    (( $1 % 2 == 0 ))
}
if is_even 4; then echo "even"; fi

# Return a value through a nameref instead of a subshell (Bash 4.3+)
get_config() {
    local -n out=$1
    out="value"
}
get_config cfg; echo "$cfg"

return only sets an exit status (0-255). Return data by printing it ($(fn)) or via a nameref. Variables are global unless declared local.

Option Parsing with getopts

verbose=false
while getopts ":vo:h" opt; do
    case $opt in
        v) verbose=true ;;
        o) output=$OPTARG ;;
        h) usage; exit 0 ;;
        :) die "-$OPTARG needs a value" ;;
        \?) die "unknown option -$OPTARG" ;;
    esac
done
shift $((OPTIND - 1))         # "$@" is now the remaining positional args

getopts only handles short options (-v). For --long options use a while/case loop like the script template below.


File Operations & Redirection

Redirection

cmd > file                    # stdout to file (overwrite)
cmd >> file                   # stdout to file (append)
cmd 2> file                   # stderr to file
cmd &> file                   # stdout + stderr to file
cmd > /dev/null 2>&1          # Discard all output
cmd 2>&1 > file               # Order matters: stderr goes to the terminal, stdout to file
echo "error" >&2              # Write to stderr
cmd1 | cmd2                   # Pipe stdout to next command
cmd1 |& cmd2                  # Pipe stdout + stderr
cmd <<< "string"              # Here-string input
cmd | tee file                # Show output and save it (tee -a to append)
diff <(cmd1) <(cmd2)          # Process substitution: command output as a file
exec > >(tee -a run.log) 2>&1 # From here on, log all script output to a file too

Here Document

cat <<EOF
Hello $name
Today is $(date)
EOF

# No variable expansion
cat <<'EOF'
Literal $variable and $(command)
EOF

# <<- strips leading TABS (not spaces), so you can indent the body
	cat <<-EOF
	indented with tabs
	EOF

# Write a file with sudo
sudo tee /etc/app.conf > /dev/null <<'EOF'
key=value
EOF

Common File Operations

# Find files
find . -name "*.log" -type f
find . -mtime -7 -name "*.tmp" -delete
find . -size +100M -type f
find . -type d -name node_modules -prune -o -type f -name "*.js" -print   # skip a dir
find . -type f -newer ref.txt          # modified after ref.txt
find . -name "*.sh" -exec chmod +x {} +

# Temp files that clean themselves up
tmp=$(mktemp)                 # mktemp -d for a directory
trap 'rm -f "$tmp"' EXIT

# Create / copy / move
mkdir -p a/b/c                # create parents
cp -a src/ dst/               # archive mode: keep perms, times, symlinks
rsync -av --delete src/ dst/  # sync dirs (trailing slash = contents)
ln -s target linkname         # symlink

# Compare files
diff file1 file2
diff -u old new > patch.diff  # Unified diff

Text Processing

grep

grep "pattern" file           # Search in file
grep -r "pattern" dir/        # Recursive search
grep -i "pattern" file        # Case insensitive
grep -n "pattern" file        # Show line numbers
grep -c "pattern" file        # Count matches
grep -l "pattern" dir/*       # List files with matches
grep -v "pattern" file        # Invert match (exclude)
grep -E "regex" file          # Extended regex (egrep)
grep -o "pattern" file        # Only matching part
grep -A 3 "pattern" file      # 3 lines after match
grep -B 3 "pattern" file      # 3 lines before match
grep -P "\d{3}-\d{4}" file    # Perl regex (GNU grep only; not on macOS)
grep -w "word" file           # Whole word only
grep -F "a.b[c]" file         # Fixed string, no regex
grep -q "pattern" file        # Quiet: just the exit status (for if)
grep -rn --include="*.py" "TODO" .   # Recursive, only .py files
grep -e foo -e bar file       # Multiple patterns

rg (ripgrep) is a faster recursive grep that respects .gitignore: rg -n "TODO" -g '*.py'.

sed

sed 's/old/new/' file         # Replace first per line
sed 's/old/new/g' file        # Replace all
sed -i 's/old/new/g' file     # Edit in place
sed -n '5,10p' file           # Print lines 5-10
sed '/pattern/d' file         # Delete matching lines
sed '/^$/d' file              # Delete empty lines
sed 's/^/    /' file          # Add indent
sed -E 's/([0-9]+)/[\1]/g'   # Extended regex with groups
sed 's|/usr/local|/opt|g'     # Any delimiter, handy for paths
sed -i.bak 's/a/b/' file      # In place, keep a backup (works on GNU and macOS)
sed '3i\new line' file        # Insert before line 3 (GNU)
sed -n '/start/,/end/p' file  # Print a range between two patterns

sed -i without a suffix is GNU-only; on macOS/BSD it needs sed -i '' 's/a/b/' file.

awk

awk '{print $1}' file         # Print first column
awk '{print $NF}' file        # Print last column
awk -F: '{print $1}' /etc/passwd  # Custom delimiter
awk 'NR==5' file              # Print line 5
awk 'NR>=5 && NR<=10' file    # Print lines 5-10
awk '{sum += $1} END {print sum}' file  # Sum column
awk '{print NR": "$0}' file   # Add line numbers
awk '/pattern/ {print $2}'    # Print col 2 of matching lines
awk '!seen[$0]++' file        # Remove duplicate lines
awk -v min=10 '$3 > min' file # Pass a shell value in with -v
awk '{c[$1]++} END {for (k in c) print c[k], k}' file   # Count by column 1
awk 'BEGIN {OFS=","} {print $1, $3}' file               # Output as CSV
awk '{printf "%-10s %5.2f\n", $1, $2}' file             # Formatted columns

jq (JSON Processing)

jq '.' file.json              # Pretty print
jq '.name' file.json          # Get field
jq '.users[0]' file.json      # Array index
jq '.users[].name' file.json  # Iterate array
jq '.[] | select(.age > 30)'  # Filter
jq '{name: .first, age: .years}' # Reshape
jq -r '.name' file.json       # Raw output (no quotes)
jq 'length' file.json         # Array/object length
jq 'keys' file.json           # Object keys
jq 'map(.price * .qty)'       # Map over array
jq '[.[] | select(.active)]'  # Filter into array
jq -c '.[]' file.json         # One compact JSON object per line
jq --arg n "$name" '.[] | select(.name == $n)'   # Pass shell vars safely
jq -n --arg k v '{($k): 1}'   # Build JSON from scratch
jq '.a.b // "default"'        # Fallback if null/missing
jq -r '.[] | [.id, .name] | @tsv'   # Tab-separated output (@csv for CSV)
jq '.version = "2.0"' f.json > tmp && mv tmp f.json   # "Edit in place"

sort, uniq, cut, tr

sort file                     # Sort alphabetically
sort -n file                  # Sort numerically
sort -r file                  # Reverse sort
sort -k2 -t, file             # Sort by column 2, comma delimited
sort -u file                  # Sort and deduplicate

uniq file                     # Remove consecutive duplicates
uniq -c file                  # Count occurrences
sort file | uniq -c | sort -rn  # Frequency count

cut -d: -f1 /etc/passwd       # Extract field 1
cut -c1-10 file               # Extract chars 1-10

tr 'a-z' 'A-Z' < file         # Uppercase
tr -d '\r' < file              # Remove carriage returns
tr -s ' ' < file               # Squeeze repeated spaces

head -n 20 file               # First 20 lines
tail -n 20 file               # Last 20 lines
tail -n +2 file                # Everything from line 2 (skip a header)
wc -l file                     # Count lines
paste -sd, file                # Join lines with commas
xargs -0 -n1 echo < list0      # One arg per command, NUL-separated input

Process Management

CommandDescription
cmd &Run in background
jobsList background jobs
fg %1Bring job 1 to foreground
bg %1Continue job 1 in background
Ctrl+ZSuspend current process
Ctrl+CKill current process (SIGINT)
kill PIDTerminate process (SIGTERM)
kill -9 PIDForce kill (SIGKILL)
pkill -f patternKill by name pattern
nohup cmd &Run immune to hangup
disown %1Detach job from shell
waitWait for all background jobs
wait $PIDWait for specific process
wait -nWait for the next background job to finish (Bash 4.3+)
xargs -P 4Run 4 parallel processes
timeout 30s cmdKill cmd if it runs longer than 30s (exit code 124)
time cmdMeasure how long a command takes
pgrep -af patternFind processes by command line

Trap (Signal Handling)

cleanup() {
    rm -f "$tmpfile"
    echo "Cleaned up"
}
trap cleanup EXIT             # Run on script exit (also after Ctrl+C or kill in Bash)
trap cleanup SIGINT SIGTERM   # Run on Ctrl+C or kill
# Using both EXIT and INT/TERM can run cleanup twice; usually EXIT alone is enough.

trap 'echo "failed at line $LINENO: $BASH_COMMAND" >&2' ERR   # Report where set -e fired

Debugging

bash -n script.sh             # Syntax check only
bash -x script.sh             # Trace every command
set -x; ...; set +x           # Trace just a section
PS4='+ ${BASH_SOURCE}:${LINENO}: ' bash -x script.sh   # Trace with file:line
shellcheck script.sh          # Lint: catches quoting bugs and most gotchas below

Interactive Shortcuts

Keys / syntaxAction
Ctrl+RSearch history backwards (press again for older)
Ctrl+A / Ctrl+EStart / end of line
Ctrl+W / Ctrl+U / Ctrl+KDelete word before / to start / to end
Alt+.Insert last argument of previous command
Ctrl+LClear screen
!!Previous command (sudo !!)
!$Last argument of previous command
^old^newRe-run previous command with a substitution
cd -Back to previous directory
pushd dir / popdDirectory stack

Common One-Liners

# Watch a command every 2 seconds
watch -n 2 'kubectl get pods'

# Parallel execution with xargs (-print0/-0 keeps filenames with spaces intact;
# ImageMagick 7 renamed `convert` to `magick`)
find . -name "*.png" -print0 | xargs -0 -P 4 -I{} magick {} -resize 50% {}

# Find and replace across files
find . -name "*.py" -exec sed -i 's/old/new/g' {} +

# Count lines of code (xargs | wc | tail -1 undercounts when xargs splits into batches)
find . -name "*.go" -print0 | xargs -0 cat | wc -l

# Monitor log file for errors
tail -f /var/log/app.log | grep --line-buffered "ERROR"

# List top 10 largest files
find . -type f -exec du -h {} + | sort -rh | head -10

# Show disk usage by directory
du -sh */ | sort -rh

# HTTP request with curl
curl -s https://api.example.com/data | jq '.'

# Generate random password
openssl rand -base64 32

# Show open ports
ss -tlnp

# Archive with progress
tar cf - dir/ | pv | gzip > dir.tar.gz

# Diff two commands
diff <(sort file1) <(sort file2)

# Repeat a command until it succeeds
until curl -sf http://localhost:8080/health; do sleep 1; done

# CSV to columns
column -t -s, data.csv

# Remove all but the 5 most recent files (breaks on names with spaces or newlines)
ls -t | tail -n +6 | xargs rm -f
ls -t | tail -n +6 | xargs -d '\n' rm -f    # GNU: OK with spaces

# Retry with backoff
for i in 1 2 3 4 5; do cmd && break; sleep $((2**i)); done

# Run something in another directory without cd-ing back
(cd /tmp && make)

# Quick HTTP server for the current dir
python3 -m http.server 8000

Script Template

#!/usr/bin/env bash
set -euo pipefail             # Exit on error, unset var, pipe fail
IFS=$'\n\t'                   # Safer word splitting

readonly SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
readonly SCRIPT_NAME="$(basename "$0")"

usage() {
    cat <<EOF
Usage: $SCRIPT_NAME [options] <argument>

Options:
    -h, --help     Show this help
    -v, --verbose  Enable verbose output
    -d, --dry-run  Show what would be done
EOF
}

log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >&2; }
die() { log "ERROR: $*"; exit 1; }

main() {
    local verbose=false
    local dry_run=false

    while [[ $# -gt 0 ]]; do
        case "$1" in
            -h|--help) usage; exit 0 ;;
            -v|--verbose) verbose=true; shift ;;
            -d|--dry-run) dry_run=true; shift ;;
            *) break ;;
        esac
    done

    [[ $# -lt 1 ]] && { usage; exit 1; }

    log "Starting $SCRIPT_NAME"
    # Main logic here
}

main "$@"

When to Use X vs Y

DecisionChoice AChoice BUse A WhenUse B When
Test[[ ]][ ]Bash scripts (safer)POSIX portability needed
ShellbashshNeed arrays, [[ ]], etcMax portability
Loop inputwhile readfor f in $(cmd)Lines with spaces, large outputSimple word lists
Quotes"$var"$varAlmost alwaysNever (causes word splitting)
Subshell$(cmd)`cmd`Always (nestable, readable)Legacy scripts only
Text searchgrepawkSimple pattern matchingColumn extraction, transforms
Text replacesedawkSimple substitutionsComplex field-based logic
JSONjqgrep/sedStructured JSON dataTrivial extraction only

Test Yourself
  1. What does $? contain? The exit status of the last executed command.

  2. How do you assign a default value to a variable if it is unset? ${var:-default} (use default) or ${var:=default} (set and use default).

  3. What set flags should every production script start with? set -euo pipefail (exit on error, unset variable error, pipe failure).

  4. How do you remove the file extension from a variable? ${file%.*} (shortest from end) or ${file%%.*} (longest from end).

  5. What is the difference between $@ and $*? $@ expands each argument as a separate word; $* expands all arguments as a single string.

  6. How do you redirect both stdout and stderr to a file? cmd &> file or cmd > file 2>&1

  7. What command reads a file line by line safely (handling spaces)? while IFS= read -r line; do ... done < file.txt

  8. How do you run a command immune to hangup signals in the background? nohup cmd &

  9. What jq command filters array elements where age is greater than 30? jq '.[] | select(.age > 30)'

  10. How do you run cleanup code when a script exits, regardless of success or failure? trap cleanup EXIT

Common Gotchas

  • Unquoted variables cause word splitting. $var splits on spaces; "$var" does not. Always quote your variables.
  • [ ] vs [[ ]]. Use [[ ]] in Bash scripts -- it handles spaces in variables, supports &&/||, and does regex matching. [ ] is POSIX but fragile.
  • Spaces around = in assignment. name = "Alice" tries to run name as a command. Assignment has no spaces: name="Alice".
  • for f in $(cmd) breaks on spaces. If filenames have spaces, this breaks. Use while IFS= read -r instead.
  • ((count++)) exits a set -e script when count is 0. The expression evaluates to 0, so the command returns status 1. Use ((count += 1)), count=$((count + 1)) or ((count++)) || true.
  • set -e has holes. It is ignored inside if/while conditions, on the left of &&/||, and in functions called from those places. local x=$(cmd) also hides cmd's failure; declare first, then assign.
  • Pipes run in subshells. cat f | while read l; do n=$((n+1)); done leaves n unchanged afterwards. Use while ...; done < f or < <(cmd).
  • cd in a script without a check. cd "$dir" && rm -rf * is safe; cd "$dir"; rm -rf * deletes the current directory if cd failed. Use cd ... || exit.
  • rm -rf "$DIR/" with an empty DIR becomes rm -rf /. Use "${DIR:?}/" so an empty variable aborts.
  • GNU vs BSD tools differ. sed -i, grep -P, date -d, readlink -f, xargs -d behave differently or are missing on macOS. Install GNU coreutils or test on both.
  • Windows line endings. A script saved with CRLF fails with $'\r': command not found. Fix with sed -i 's/\r$//' script.sh or dos2unix.

One-Liner Summary

Bash is the glue language of Unix -- master variables, conditionals, set -euo pipefail, pipes, and trap to write scripts that automate anything and fail gracefully.