Cheatsheet: Bash scripting

Last updated 2026-06-21

Script basics

Start a script with a Bash shebang

#!/usr/bin/env bash

Fail fast on errors, unset variables, and pipeline failures

set -euo pipefail

Declare and read a variable

name="Ada"
echo "Hello, $name"

Use command substitution to capture command output

today=$(date +%F)

Exit with a success or failure status

exit 0
exit 1

Arguments and functions

Read positional arguments

echo "script=$0 first=$1 second=$2"

Loop over all arguments safely

for arg in "$@"; do
  echo "$arg"
done

Check the number of arguments

if [[ $# -lt 1 ]]; then
  echo "usage: $0 <file>" >&2
  exit 1
fi

Define and call a function

greet() {
  echo "Hello, $1"
}
greet "Ada"

Conditionals and tests

Use an if statement with Bash test syntax

if [[ -f "$file" ]]; then
  echo "file exists"
fi

Combine string and file tests

[[ -n "$name" && -r "$file" ]]

Use numeric comparisons

if [[ $count -ge 10 ]]; then
  echo "enough"
fi

Branch with a case statement

case "$answer" in
  y|yes) echo "confirmed" ;;
  n|no) echo "cancelled" ;;
  *) echo "unknown" ;;
esac

Check the previous command exit code

if command; then
  echo "command succeeded"
else
  echo "command failed with $?"
fi

Loops and data

Iterate over files with a for loop

for file in *.txt; do
  echo "$file"
done

Read a file line by line

while IFS= read -r line; do
  echo "$line"
done < input.txt

Use arrays and expand elements safely

files=(a.txt b.txt)
printf '%s\n' "${files[@]}"

Use common string parameter expansions

path=/var/log/app.log
echo "${path##*/}"
echo "${path%.log}"
echo "${name:-guest}"

Do integer arithmetic

count=$((count + 1))
if (( count % 2 == 0 )); then echo even; fi

Input and output

Redirect standard output and standard error

command > output.log 2> error.log

Append output and merge errors into the same file

command >> combined.log 2>&1

Send a multi-line here-doc to a command

cat <<'TEXT'
Literal $HOME is not expanded here.
TEXT

See also: