HARDCORE BLUE ← Home
Field and programming notes

Bash Pattern Notebook 2: Grass Roots

A guide for learning Bash from the ground up. The aim is to hold the shape of the language in your head (patterns, builtins and control flow) so you can write small OS programs from memory. Read one part, close it, then rewrite its patterns from memory in a scratch file.

Part 1: The Mental Model (5 rules)

  1. Everything is a command. A line is command arg1 arg2. Even [ and echo are commands.
  2. Exit status is truth. 0 = success = true. Anything else = failure = false. if, while, &&, || all just read the exit status.
  3. Bash rewrites your line before running it (expansion), then splits it into words, then runs it.
  4. Unquoted variables get word-split and globbed. Always write "$var".
  5. Data flows through three streams: 0 stdin, 1 stdout, 2 stderr. Pipes and redirects just rewire them.

Order of expansion (rough): brace {a,b} → tilde ~ → $var / $(cmd) / $((math)) → word splitting → globbing * → quote removal.

Quoting in one table

Syntax Meaning
"..." expands $var, $(cmd); no splitting. Default choice.
'...' fully literal. Nothing expands.
\x escape one character
$'a\tb' ANSI-C quoting (tabs, newlines)

Exit status cheat codes

Code Meaning
0 success
1 general failure
2 misuse of a command
126 found but not executable
127 command not found
128+n killed by signal n (130 = Ctrl-C)

Read the last status with $?.

Part 2: Script Skeleton

#!/usr/bin/env bash
set -euo pipefail          # strict mode (see traps below)

usage() {
    echo "Usage: ${0##*/} <arg>" >&2
    exit 1
}

main() {
    [[ $# -ge 1 ]] || usage
    local target=$1
    echo "Working on: $target"
}

main "$@"

Run it: chmod +x script.sh && ./script.sh arg

Strict mode, decoded:

Part 3: Builtins vs Keywords vs External Commands

Three kinds of "words" at the start of a line:

Kind Examples Lives in
Keyword if then else fi for while do done case esac function [[ ]] (( )) the bash grammar itself
Builtin cd echo read printf test [ declare local trap inside the bash process
External ls grep sed awk find date sleep cat a file on disk (/usr/bin/...)

Why builtins matter: they are fast (no new process), and some must be builtins because they change the shell itself (cd, export, exit, source).

Explore the system yourself

type ls            # what kind of thing is this?
type -a echo       # show all versions (builtin AND /usr/bin/echo)
help read          # built-in manual for a builtin
compgen -b         # list all builtins
compgen -k         # list all keywords

The builtin map (by job)

Move around and inspect

Builtin Job
cd pwd change / show directory
pushd popd dirs directory stack (bookmark and return)
type command hash help find out what a name is
alias unalias shortcuts

Input and output

Builtin Job
echo print (simple)
printf print with formatting (prefer this for anything tricky)
read read input into variables
mapfile / readarray read lines into an array

Variables and settings

Builtin Job
declare / typeset create variable with attributes (-i int, -a array, -A assoc, -r readonly)
local variable scoped to a function
export pass variable to child processes
readonly unset lock / remove
set shopt change shell options
shift drop $1, slide the rest down
getopts parse -v -o file style options

Testing and math

Builtin Job
test / [ classic tests
let arithmetic ((( )) is nicer)
true false : do nothing, success / failure / success

Flow control

Builtin Job
break continue leave / skip loop iteration
return leave a function with a status
exit leave the script with a status

Running things

Builtin Job
source / . run a file inside the current shell
eval run a string as code (avoid unless needed)
exec replace the shell with a command
builtin command bypass functions/aliases

Processes and signals

Builtin Job
jobs bg fg disown background job control
wait wait for background jobs
kill send a signal
trap run code on a signal or on exit
ulimit umask resource limits / default permissions

Note: ls, grep, sed, awk, find, date, sleep, mkdir, rm, cat are not builtins. They are separate programs. Bash is the glue.

Part 4: Variables and Expansion Patterns

Basics

name="Jackie"            # NO spaces around =
echo "$name"
echo "${name}_backup"    # braces when next to other text
today=$(date +%F)        # command substitution
total=$(( 5 + 3 ))       # arithmetic substitution

Special parameters

Var Meaning
$0 script name
$1 $2 ... positional arguments
$# number of arguments
"$@" all arguments, each kept separate (use this one)
$* all arguments as one string
$? last exit status
$$ this shell's PID
$! PID of last background job

Parameter expansion (the string toolbox)

Pattern Result
${var:-default} use default if var unset/empty
${var:=default} same, and also assign it
${var:?message} error and exit if unset/empty
${#var} length
${var#pat} / ${var##pat} strip shortest / longest match from the front
${var%pat} / ${var%%pat} strip shortest / longest match from the back
${var/old/new} / ${var//old/new} replace first / all
${var^^} / ${var,,} UPPER / lower case
${var:2:5} substring (offset 2, length 5)

Memory trick: # is on the left of the keyboard number row (front), % is on the right (back).

Two you will use constantly:

file="/var/log/syslog.gz"
echo "${file##*/}"    # syslog.gz   (basename)
echo "${file%.*}"     # /var/log/syslog   (strip extension)

Arrays

fruits=(apple banana cherry)
echo "${fruits[0]}"        # apple
echo "${fruits[@]}"        # all elements
echo "${#fruits[@]}"       # count
fruits+=(date)             # append
for f in "${fruits[@]}"; do echo "$f"; done

Associative arrays (key/value, bash 4+)

declare -A age
age[alice]=30
age[bob]=25
echo "${age[alice]}"
for key in "${!age[@]}"; do echo "$key is ${age[$key]}"; done

Part 5: Tests (the question-asking tools)

Prefer [[ ... ]] for strings and files, and (( ... )) for numbers.

File tests

Test True when
-e f exists
-f f regular file
-d f directory
-L f symlink
-r f -w f -x f readable / writable / executable
-s f exists and is not empty
f1 -nt f2 f1 is newer than f2

String tests

Test True when
-z "$s" empty
-n "$s" not empty
[[ $a == $b ]] equal
[[ $a != $b ]] not equal
[[ $s == *.log ]] glob match (unquoted right side)
[[ $s =~ ^[0-9]+$ ]] regex match (captures in BASH_REMATCH)

Number tests

(( count > 5 ))          # preferred: reads like normal math
(( a == b ))
[[ $a -gt $b ]]          # old style: -eq -ne -lt -le -gt -ge

Combining

[[ -f $file && -r $file ]]     # and
[[ $a == x || $b == y ]]       # or
[[ ! -d $dir ]]                # not

Short-circuit idioms

mkdir -p "$dir" && cd "$dir"            # run second only if first worked
[[ -f $cfg ]] || { echo "no config" >&2; exit 1; }   # guard clause

Part 6: Control Flow (the five shapes)

1. if / elif / else

if [[ -d $path ]]; then
    echo "directory"
elif [[ -f $path ]]; then
    echo "file"
else
    echo "something else"
fi

if accepts any command, not just tests:

if grep -q "root" /etc/passwd; then echo "found root"; fi

2. case (pattern matching a value)

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

Each branch ends with ;;. * is the default.

3. for (loop over a list)

for f in *.log; do echo "$f"; done          # glob
for n in {1..5}; do echo "$n"; done         # range
for item in "${array[@]}"; do echo "$item"; done
for ((i = 0; i < 5; i++)); do echo "$i"; done   # C style

4. while / until (loop on a condition)

while (( count < 5 )); do
    echo "$count"
    (( count++ ))
done

until ping -c1 -W1 8.8.8.8 &>/dev/null; do
    echo "waiting for network..."; sleep 2
done

The most important loop in bash: read a file line by line

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

5. select (instant menu)

PS3="Choose: "
select choice in status disk quit; do
    case $choice in
        status) uptime ;;
        disk)   df -h ;;
        quit)   break ;;
        *)      echo "invalid" ;;
    esac
done

Loop controls

break leaves the loop. continue jumps to the next iteration.

Part 7: Functions

log() {
    local level=$1; shift
    printf '[%s] %s: %s\n' "$(date +%T)" "$level" "$*"
}

is_root() {
    (( EUID == 0 ))        # status of last command becomes the return value
}

log INFO "starting"
if is_root; then log INFO "running as root"; fi

Rules:

Part 8: Input, Output and Redirection

Syntax Meaning
cmd > file stdout to file (overwrite)
cmd >> file stdout to file (append)
cmd < file file into stdin
cmd 2> err.txt stderr to file
cmd > out 2>&1 stdout and stderr to same file
cmd &> file same, shorthand
cmd > /dev/null 2>&1 throw all output away
cmd1 | cmd2 pipe stdout of 1 into stdin of 2
echo "msg" >&2 print to stderr (errors go here)

Here-doc and here-string

cat <<EOF
Host: $(hostname)
Date: $(date)
EOF

grep -c "error" <<< "$text"      # feed a string as stdin

Process substitution

diff <(sort a.txt) <(sort b.txt)       # treat command output as a file

read patterns

read -r -p "Your name: " name              # prompt
read -r -s -p "Password: " pw; echo        # silent
read -r -n1 -p "Continue? [y/n] " yn       # single key
read -r first rest <<< "hello big world"  # split into variables
mapfile -t lines < file.txt                # whole file into array

printf (use it instead of echo for formatting)

printf '%s\n' "text"                  # string
printf '%-15s %5d\n' "$name" "$num"   # left-pad string, right-align number
printf '%.2f\n' 3.14159               # 3.14

Part 9: Arguments, Options and Cleanup

Positional arguments

[[ $# -eq 2 ]] || { echo "Usage: $0 src dst" >&2; exit 1; }
src=$1
dst=$2

Process all arguments

while (( $# > 0 )); do
    echo "Arg: $1"
    shift
done

getopts (flags like -v -o file)

verbose=0; out=""
while getopts ":vo:h" opt; do
    case $opt in
        v)  verbose=1 ;;
        o)  out=$OPTARG ;;
        h)  usage ;;
        :)  echo "-$OPTARG needs a value" >&2; exit 1 ;;
        \?) echo "Unknown option: -$OPTARG" >&2; exit 1 ;;
    esac
done
shift $(( OPTIND - 1 ))     # remaining args are now $1, $2...

A colon after a letter (o:) means that option takes a value.

trap (always clean up)

tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT          # runs however the script ends
trap 'echo "interrupted"; exit 130' INT

Part 10: Pattern Recipes (copy, then rewrite from memory)

Confirm before doing something dangerous

read -r -p "Delete $dir? [y/N] " ans
[[ $ans == [yY] ]] || exit 0

Retry a command

for attempt in {1..5}; do
    if some_command; then break; fi
    echo "attempt $attempt failed" >&2
    sleep 2
done

Check a tool exists

command -v jq >/dev/null || { echo "jq is required" >&2; exit 1; }

Timestamped filename

backup="backup_$(date +%Y%m%d_%H%M%S).tar.gz"

Loop over files safely (spaces in names)

find . -type f -name '*.log' -print0 |
while IFS= read -r -d '' f; do
    echo "Found: $f"
done

Count things (associative array tally)

declare -A seen
for word in apple pear apple fig apple; do
    (( seen[$word]++ )) || true
done

Default argument

dir=${1:-.}          # use $1, or current directory

Run only as root

(( EUID == 0 )) || { echo "run as root" >&2; exit 1; }

Part 11: Three Mini Programs

1. Disk space warning

#!/usr/bin/env bash
set -euo pipefail
threshold=${1:-80}

df -P | tail -n +2 | while read -r fs size used avail pct mount; do
    use=${pct%\%}
    if (( use >= threshold )); then
        printf '%-20s %s%% used\n' "$mount" "$use"
    fi
done

Uses: default arg, pipe into while read, parameter expansion, (( )), printf.

2. Evidence hash manifest

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

usage() { echo "Usage: ${0##*/} <directory>" >&2; exit 1; }
[[ $# -eq 1 ]] || usage
dir=$1
[[ -d $dir ]] || { echo "Not a directory: $dir" >&2; exit 1; }

# write the manifest OUTSIDE the directory being hashed
out="/tmp/manifest_$(date +%Y%m%d_%H%M%S).sha256"
find "$dir" -type f -print0 | sort -z | xargs -0 sha256sum > "$out"
printf 'Hashed %d files -> %s\n' "$(wc -l < "$out")" "$out"

Uses: guard clauses, $(...), null-safe find, redirection. Verify later with sha256sum -c manifest.sha256.

3. Failed login tally

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

log=${1:-/var/log/auth.log}
[[ -r $log ]] || { echo "Cannot read $log" >&2; exit 1; }

re='Failed password.*from ([0-9.]+)'
declare -A count

while IFS= read -r line; do
    if [[ $line =~ $re ]]; then
        ip=${BASH_REMATCH[1]}
        (( count[$ip]++ )) || true
    fi
done < "$log"

for ip in "${!count[@]}"; do
    printf '%6d  %s\n' "${count[$ip]}" "$ip"
done | sort -rn

Uses: regex capture, associative array, read loop, pipe to sort.

Part 12: Traps and Gotchas

Gotcha Fix
x = 5 fails no spaces: x=5
[ $a == $b ] breaks on empty/spaces use [[ ... ]] and quote: "$a"
rm $file with spaces in the name rm "$file"
cmd | while read loses variables set inside feed from a file or < <(cmd) instead
(( n++ )) returns failure when n was 0, which kills a set -e script (( n++ )) || true, or use n=$(( n + 1 ))
for f in $(ls) for f in *
echo behaves differently with -n/-e across systems printf
function inside a pipeline runs in a subshell variables set there do not survive
set -e is not a full safety net (ignored inside if tests, || chains) still check critical commands explicitly

Debug mode: run bash -x script.sh to see every command as it executes, or add set -x / set +x around a section.

Lint it: shellcheck script.sh catches most of the table above automatically.

Part 13: One-Page Cheat Sheet

SHAPE                      SYNTAX
─────────────────────────────────────────────────────────────
shebang                    #!/usr/bin/env bash
strict mode                set -euo pipefail
variable                   x=5            "$x"   "${x}"
command output             $(cmd)
math                       $(( a + b ))   (( a < b ))
if                         if [[ test ]]; then ...; elif ...; else ...; fi
case                       case $v in a|b) ...;; *) ...;; esac
for list                   for x in a b c; do ...; done
for C-style                for ((i=0;i<n;i++)); do ...; done
while                      while cond; do ...; done
read lines                 while IFS= read -r l; do ...; done < file
function                   name() { local x=$1; ...; }
args                       $1 $2  "$@"  $#  shift
default                    ${v:-fallback}
strip front / back         ${v##*/}   ${v%.*}
test file                  -e -f -d -r -w -x -s
test string                -z -n == != =~
and / or                   &&  ||
redirect                   > >> < 2> 2>&1 &>
cleanup                    trap 'cmd' EXIT

Part 14: Recall Drills

Do these without looking. Check afterwards, then repeat the ones you missed a day later.

Level 1: shapes 1. Write the script skeleton with shebang, strict mode and a usage function. 2. Write an if / elif / else that tells you if a path is a file, directory or missing. 3. Write a case that accepts start, stop, status and complains about anything else. 4. Write a for loop over *.txt that prints each name and its line count.

Level 2: patterns 5. Read a file line by line and print only lines containing "error". 6. Write a function confirm "question" that returns success only if the user types y. 7. Strip the extension from a filename and add .bak, using parameter expansion only. 8. Count how many times each word appears in a list, using an associative array.

Level 3: programs 9. A script that takes a directory and prints the 5 largest files in it. 10. A script that checks if a list of services are active and reports OK or DOWN for each. 11. A script that backs up a folder to a timestamped .tar.gz, refusing to run if the folder does not exist. 12. A menu with select offering: show date, show disk, show memory, quit.

Self-test question for every script you write: What are my inputs? What can go wrong? What happens on failure? What gets cleaned up?

Where Next