Bash Conditionals, Loops, and Functions

Bash if/elif/case logic, test expressions, loops, functions, return codes, and robust control-flow patterns.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Tests and Conditionals
Test whether file exists
if [[ -f /etc/hosts ]]; then echo yes; fi

# Check whether a regular file exists.

Test whether directory exists
if [[ -d /var/log ]]; then echo yes; fi

# Check whether a directory exists.

Test for empty string
if [[ -z "$name" ]]; then echo empty; fi

# Check whether a string is empty.

Compare strings
if [[ "$env" == 'prod' ]]; then echo deploy; fi

# Compare string values.

Compare integers
if (( count > 10 )); then echo large; fi

# Use arithmetic context for integer comparisons.

Test command success
if grep -q needle file.txt; then echo found; fi

# Use a command directly as the condition.

Pattern matching with case
case "$ext" in
  jpg|png) echo image ;;
  txt) echo text ;;
  *) echo other ;;
esac

# Match one variable against several patterns.

## Loops
For loop over words
for f in *.log; do echo "$f"; done

# Iterate over a list or glob.

C-style arithmetic for loop
for ((i=0; i<5; i++)); do echo "$i"; done

# Use arithmetic syntax in Bash for loops.

While read loop
while IFS= read -r line; do printf '%s
' "$line"; done < file.txt

# Read input line by line safely.

Until loop
until curl -sf http://localhost:8080/health; do sleep 1; done

# Run loop until command succeeds.

Use break and continue
for n in {1..5}; do [[ $n -eq 3 ]] && continue; echo "$n"; done

# Skip or exit loop iterations.

Simple select menu
select choice in start stop status quit; do echo "$choice"; break; done

# Create a numbered shell menu.

## Functions
Define a function
greet() { echo "Hello, $1"; }

# Define a shell function.

Call a function
greet Jonathan

# Invoke a shell function with arguments.

Use local variable in function
work() { local dir=${1:-/tmp}; cd "$dir" || return 1; pwd; }

# Keep function internals from leaking into caller scope.

Return status from function
validate() { [[ -n "$1" ]] || return 1; }

# Return a status code from a function.

Return data via stdout
slugify() { tr '[:upper:] ' '[:lower:]-' <<< "$1"; }
slug=$(slugify 'Hello World')

# Emit data to stdout and capture it with command substitution.

Trace shell functions
set -x
my_func() { echo ok; }
my_func
set +x

# Trace function execution during debugging.

## Script Safety
Enable stricter script mode
set -euo pipefail

# Exit on errors, unset variables, and pipeline failures.

Set safer IFS
IFS=$'
\t'

# Restrict word splitting to newline and tab.

Run cleanup on exit
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT

# Register cleanup logic for normal exit.

Print error location
trap 'echo "error on line $LINENO"' ERR

# Add basic error diagnostics to a script.

Shellcheck directive example
# shellcheck disable=SC2086
echo $unquoted

# Document intentional exceptions for static analysis.