Skip to content

Bash cheat sheet

Bash scripting syntax. For individual commands (ls, grep, find…) see the Linux commands cheat sheet.

25 entries

Script basics

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

Shebang + strict mode: exit on error, unset vars, failed pipes.

name="Ada"
echo "Hello, $name"
echo 'no $expansion here'

No spaces around =; double quotes expand, single quotes don’t.

today=$(date +%F)

Command substitution.

echo $(( 3 * 4 ))

Integer arithmetic.

echo "$0 $1 $# $@ $?"

Script name, first arg, arg count, all args, last exit code.

Conditionals

if [[ -f config.yml ]]; then
  echo "found"
elif [[ -d config ]]; then
  echo "dir"
else
  echo "missing"
fi

Use [[ ]] in bash.

[[ $a == "$b" ]]  [[ $n -gt 5 ]]  [[ -z $s ]]  [[ $s =~ ^[0-9]+$ ]]

String equal, numeric greater, empty, regex match.

command -v jq >/dev/null || echo "install jq"

Short-circuit with && and ||.

case "$1" in
  start) run ;;
  stop|halt) halt ;;
  *) echo "usage: $0 start|stop" ;;
esac

case statement.

Loops

for f in *.log; do
  echo "$f"
done

Loop over files (quote "$f").

for i in {1..5}; do echo "$i"; done

Brace range.

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

Read a file line by line safely.

Functions & arrays

greet() {
  local who="${1:-world}"
  echo "Hello, $who"
}
greet Ada

Functions take positional args; local scopes variables.

arr=(a b c)
echo "${arr[0]} ${#arr[@]}"
for x in "${arr[@]}"; do echo "$x"; done

Indexed arrays.

declare -A ages=([ada]=36 [alan]=41)
echo "${ages[ada]}"

Associative arrays (bash 4+).

Parameter expansion

${var:-default}  ${var:=default}

Use default / assign default if unset or empty.

${file%.txt}  ${path##*/}

Strip suffix; basename.

${s/foo/bar}  ${s//foo/bar}

Replace first / all.

${#s}  ${s:0:3}  ${s^^}

Length, substring, uppercase.

Redirection

cmd > out.txt 2>&1
cmd &> out.txt

stdout and stderr to a file.

cmd >> log.txt

Append.

cmd 2>/dev/null

Discard errors.

cat <<EOF
Hello $USER
EOF

Here-document.

diff <(sort a.txt) <(sort b.txt)

Process substitution.

trap 'rm -f "$tmp"' EXIT

Clean up when the script exits.

Frequently asked questions

Why should I quote variables in bash?

Unquoted variables are split on whitespace and glob-expanded, so a file named "my file.txt" becomes two arguments. Quoting ("$var") passes the value intact.

[ ] vs [[ ]]?

[ ] is the POSIX test command; [[ ]] is a bash keyword that avoids word-splitting surprises and supports && ||, pattern matching and =~ regex. Use [[ ]] in bash scripts.

What does set -euo pipefail do?

-e exits on any failing command, -u treats unset variables as errors, and -o pipefail makes a pipeline fail if any command in it fails, not just the last.

Related cheat sheets