Skip to main content

83 entries · 7 sections

Bash Scripting Cheat Sheet

The bash syntax you need to write a script that will not embarrass you six months later: safe defaults, quoting, parameter expansion, tests, loops, functions, redirection and the special variables. Written for bash 4 and later, which is what servers and containers run.

Script setup and safety

SyntaxWhat it does
#!/usr/bin/env bashShebang that finds bash wherever it lives on the user's PATH.
set -eExit as soon as any command fails.
set -uTreat the use of an unset variable as an error.
set -o pipefailA pipeline fails if any stage fails, not just the last one.
set -euo pipefailAll three together — the standard opening line of a script you intend to trust.
set -xPrint each command before running it. The fastest debugger bash has.
IFS=$'\n\t'Stop word-splitting on spaces. Pairs with set -euo pipefail as the strict-mode preamble.
trap 'rm -f "$tmp"' EXITRun cleanup whenever the script exits, however it exits.
chmod +x script.shMake the script executable so ./script.sh works.
shellcheck script.shLint the script. It catches quoting bugs that will not show up until production.

Variables and arrays

SyntaxWhat it does
name="Ada"Assign a variable. No spaces around the equals sign.
echo "$name"Always quote expansions; unquoted ones word-split and glob-expand.
readonly PI=3.14Declare a constant.
local x=1Scope a variable to the function it is declared in.
export PATH="$PATH:/opt/bin"Put a variable into the environment of child processes.
count=$((count + 1))Integer arithmetic.
now=$(date +%F)Capture a command's output into a variable.
arr=(a b c)Define an indexed array.
"${arr[@]}"Every element, each as its own quoted word. This is almost always what you want.
"${#arr[@]}"The number of elements.
arr+=(d)Append to an array.
declare -A map; map[key]=valAn associative array — bash 4 and later, so not macOS's system bash 3.2.

Parameter expansion

SyntaxWhat it does
${var:-default}Use default when var is unset or empty, without assigning anything.
${var:=default}The same, and assign the default back to var.
${var:?message}Abort with a message when var is unset. Good for required arguments.
${var:+alt}Use alt only when var is set — the inverse of :-.
${#var}The length of the value.
${var#prefix} / ${var##prefix}Strip the shortest / longest matching prefix.
${var%suffix} / ${var%%suffix}Strip the shortest / longest matching suffix.
${var/old/new}Replace the first occurrence.
${var//old/new}Replace every occurrence.
${var^^} / ${var,,}Upper-case / lower-case the whole value (bash 4+).
${var:2:5}Substring: five characters starting at index 2.
${file%.*} and ${file##*/}The filename without its extension, and the basename without its directory.

Conditionals

SyntaxWhat it does
if [[ $a == "x" ]]; then ... fiString comparison. Prefer [[ ]] to [ ] in bash — it does not word-split.
[[ $a != $b ]]Not equal.
[[ $a == x* ]]Glob match. The right-hand side must be unquoted for the glob to apply.
[[ $a =~ ^[0-9]+$ ]]Regex match. The pattern must be unquoted, and captures land in ${BASH_REMATCH[@]}.
[[ -z "$a" ]] / [[ -n "$a" ]]The string is empty / is not empty.
[[ -f path ]]Exists and is a regular file.
[[ -d path ]]Exists and is a directory.
[[ -e path ]] / [[ -r path ]] / [[ -x path ]]Exists / is readable / is executable.
(( a > b ))Arithmetic comparison. Use this for numbers rather than the string operators.
[[ $a -eq $b ]]The test-style numeric operators: -eq -ne -lt -le -gt -ge.
if cmd; then ... fiBranch on a command's exit status directly — no test needed.
cmd && echo ok || echo failShort-circuit success and failure in one line. Fine for one-liners, fragile in scripts.
case "$x" in a) ...;; *) ...;; esacMulti-way branch on glob patterns.

Loops and functions

SyntaxWhat it does
for f in *.txt; do ... doneLoop over a glob. This handles spaces in filenames correctly; parsing ls does not.
for i in {1..10}; do ... doneLoop over a numeric range.
for ((i=0; i<10; i++)); do ... doneC-style loop.
while read -r line; do ... done < fileRead a file line by line. -r stops backslashes being interpreted.
while true; do ...; sleep 5; donePoll forever.
until cmd; do sleep 1; doneRetry until a command finally succeeds.
break / continueLeave the loop / skip to the next iteration.
greet() { echo "hi $1"; }Define a function. Call it as greet Ada — no parentheses at the call site.
return 1Set a function's exit status. Use exit only when you mean to end the script.
"$@"Every argument, each separately quoted. Almost always the right choice.
"$*"Every argument joined into a single string.
shiftDrop $1 and renumber the rest — the core of an option-parsing loop.

Input, output and pipes

SyntaxWhat it does
cmd > fileSend stdout to a file, replacing its contents.
cmd >> fileAppend stdout to a file.
cmd 2> err.logRedirect stderr only.
cmd > out.log 2>&1Send both streams to the same file. Order matters — 2>&1 must come after.
cmd &> out.logThe bash shorthand for exactly that.
cmd < fileFeed a file in as stdin.
cmd <<< "text"Feed a single string in as stdin — a here-string.
cat <<'EOF' > f ... EOFA here-document. Quoting EOF stops variable expansion inside it.
a | bPipe a's stdout into b's stdin.
cmd | tee fileShow the output and save it at the same time.
cmd > /dev/null 2>&1Discard all output.
read -rp "Name: " namePrompt for input and store it.

Special variables and exit codes

SyntaxWhat it does
$0The script's own name as it was invoked.
$1 ... $9, ${10}Positional arguments. Past nine, the braces are required.
$#How many arguments were passed.
$?The exit status of the last command. Zero means success.
$$The process id of the current shell.
$!The process id of the last command started in the background.
$_The last argument of the previous command.
exit 0 / exit 1Finish successfully / with an error the caller can detect.
"${BASH_SOURCE[0]}"The path to this script, correct even when the script is sourced.
cd "$(dirname "${BASH_SOURCE[0]}")"Make a script run relative to its own directory rather than the caller's.
command -v jq >/dev/null || exit 1Fail early and clearly when a dependency is missing.
mktemp -dCreate a temporary directory safely instead of guessing a name in /tmp.

Worth knowing

  • Quote every expansion. "$var" and "${arr[@]}" are correct; the unquoted forms word-split on spaces and expand globs, which is how a script that worked for months breaks the day someone creates a file with a space in its name.
  • set -e is helpful but not magic: it does not trigger inside a condition, inside a && chain, or for a failing command in the middle of a pipeline. That last one is why set -o pipefail exists, and why the three-flag preamble is the usual recipe rather than set -e alone.
  • Run shellcheck on anything you intend to keep. It is a static analyser for shell that catches unquoted variables, useless uses of cat, subshell scoping mistakes and portability problems, and it explains each finding with a wiki link.

Try a snippet instead of reading about it

Reference is faster when you can run the thing. Paste a snippet into AltF Code, the free in-browser editor — real syntax highlighting for HTML, CSS, JavaScript, Python, SQL, JSON and more, with HTML, CSS and JavaScript running live in the preview. No install and no sign-up.

Open the editor

Bash Scripting — common questions

What does set -euo pipefail do?
-e exits the script as soon as a command fails, -u turns the use of an undefined variable into an error rather than an empty string, and -o pipefail makes a pipeline report failure if any stage fails rather than only the last one. Together they turn silent partial failures into loud, early ones.
What is the difference between [ ] and [[ ]] in bash?
[ is an ordinary command (test), so its arguments undergo word splitting and globbing, and unquoted empty variables cause syntax errors. [[ is bash syntax: it does not split, it supports == glob matching and =~ regex matching, and it allows && and || inside. Use [[ ]] in bash, and [ ] only when the script must run under plain POSIX sh.
How do I read a file line by line?
Use while IFS= read -r line; do ...; done < file. IFS= stops leading and trailing whitespace being trimmed and -r stops backslash escapes being interpreted, which between them preserve the line exactly as written. Reading with for line in $(cat file) splits on every space instead of every newline.
Why does my script work in the terminal but not when run by cron?
cron runs with a minimal environment: a short PATH, no shell profile, and usually /bin/sh rather than your login shell. Use absolute paths to binaries or set PATH explicitly at the top of the script, do not rely on variables your profile exports, and redirect output to a log file so you can see what actually happened.