Bash Cheatsheet

View saved

Bash scripts automate sequences of commands. Quote expansions, check exit statuses, and prefer set -euo pipefail in new scripts.

The Linux course covers everyday shell use; this sheet focuses on scripting patterns.

Scripts & variables

Shebang

First line selects the interpreter via PATH.

#!/usr/bin/env bash

Run a script

Make executable or pass to bash.

chmod +x script.sh
./script.sh
bash -n script.sh

Variables

No spaces around =. Quote expansions.

name="Ada Lovelace"
echo "$name"
user="${1:-friend}"

Arguments

$1… parameters; "$@" all args safely.

echo "count=$#"
for a in "$@"; do echo "$a"; done

Script directory

Resolve the folder containing the script.

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

Quoting & tests

Quotes

Single = literal; double = expand $var and $(...).

echo 'Home is $HOME'
echo "Home is $HOME"

[[ ]] tests

Prefer Bash [[ ]] for strings and files.

if [[ -z "${name:-}" ]]; then exit 1; fi
[[ -f "$file" && -r "$file" ]]

File tests

-f file, -d dir, -e exists, -x executable.

[[ -d "$dir" ]] || mkdir -p "$dir"

Command substitution

Capture stdout with $(...) and quote when needed.

today="$(date +%F)"

Control flow

if / else

Branch on command success or [[ ]].

if grep -q pattern file.txt; then
  echo found
fi

case

Pattern match for subcommands and options.

case "$1" in
  start) echo starting ;;
  stop) echo stopping ;;
  *) echo "usage: $0 start|stop" >&2; exit 2 ;;
esac

Loops

for, while, and C-style numeric loops.

for f in *.txt; do
  [[ -e "$f" ]] || continue
  echo "$f"
done

Functions

Use local; return status separately from stdout.

greet() {
  local who="${1:-world}"
  printf 'Hello, %s\n' "$who"
}

Safety & automation

set -euo pipefail

Exit on errors, unset vars, and failing pipeline stages.

set -euo pipefail

Exit codes

0 success; print errors to stderr.

echo "fail" >&2
exit 1

Redirects

stdout/stderr to files; combine streams.

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

Arrays

Quote "${arr[@]}" when expanding.

files=("a.txt" "b c.txt")
for f in "${files[@]}"; do echo "$f"; done

Cron peek

Use absolute paths; cron has a minimal environment.

0 7 * * * /home/ada/bin/backup.sh

Comments

One comment per signed-in account. Comments are saved with this page’s URL.