Skip to content

/cheatsheets/bash/bash-cheat-sheet

Bash cheat sheet: variables, tests, loops and expansions

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash)updated 2026-10-20
tool
Bash
versions
bash 4.x, bash 5.x
os
linux, macos, windows

A compact reference for everyday bash. Every expansion in the first block below was run in bash 5.

Variables and parameter expansion

bash
name="report.tar.gz"
echo "${name%.gz}"        # remove shortest suffix
echo "${name%%.*}"        # remove longest suffix
echo "${name#*.}"         # remove shortest prefix
echo "${#name}"           # length
echo "${name/tar/zip}"    # replace first match
echo "${missing:-default}"  # default if unset or empty
echo "${name^^}"          # uppercase (bash 4+)

Output

report.tar
report
tar.gz
13
report.zip.gz
default
REPORT.TAR.GZ
SyntaxMeaning
${var:-word}word if var is unset or empty
${var:=word}assign word if var is unset or empty
${var:?msg}exit with msg if var is unset or empty
${var:+word}word if var is set and non-empty
${var:offset:length}substring
$(command)command substitution
$((a + b))arithmetic expansion

Tests

TestTrue when
[[ -f path ]]path is a regular file
[[ -d path ]]path is a directory
[[ -e path ]]path exists
[[ -z $s ]] / [[ -n $s ]]string is empty / not empty
[[ $a == $b ]]strings are equal (right side is a glob pattern if unquoted)
[[ $s =~ regex ]]string matches the extended regex
(( a < b ))arithmetic comparison

Loops and conditionals

bash
for f in a b c; do printf '%s ' "$f"; done; echo
for ((i = 1; i <= 3; i++)); do printf '%d ' "$i"; done; echo
n=0; while (( n < 2 )); do echo "n=$n"; ((n++)); done
case "linux" in lin*) echo "matched lin*" ;; *) echo "other" ;; esac

Output

a b c
1 2 3
n=0
n=1
matched lin*

Functions and arrays

bash
greet() { local who="${1:-world}"; echo "hello, $who"; }
greet; greet errcodex
arr=(alpha beta gamma)
echo "${arr[1]} ${#arr[@]} ${arr[@]:1}"
declare -A port=([http]=80 [https]=443)
echo "${port[https]}"

Output

hello, world
hello, errcodex
beta 3 beta gamma
443

Redirection

SyntaxMeaning
cmd > filestdout to file (overwrite)
cmd >> filestdout to file (append)
cmd 2> filestderr to file
cmd > file 2>&1stdout and stderr to file
cmd &> filesame, bash shorthand
cmd < filefile as stdin
cmd <<< "text"here-string as stdin
cmd1 | cmd2stdout of cmd1 to stdin of cmd2

Script header

bash
#!/usr/bin/env bash
set -euo pipefail

See set -euo pipefail for what these options change.

Sources