HARDCORE BLUE ← Home
Field and programming notes

Bash Patterns for Beginners

A working notebook of small Bash patterns. Use them as starting points, change them for your task, and look up details when you need them.

The mental model

A Bash program mostly does three things:

  1. Runs commands such as wc or grep.
  2. Makes decisions with if.
  3. Repeats steps with loops.

Most small scripts follow this shape:

get input → check it → do the work → show the result

Before coding, answer four questions:

1. Find out what Bash already knows

Bash has its own language words and built-in commands. Programs like wc and grep are separate tools that Bash can run.

help             # Bash help topics and builtins
help if          # help for the if structure
help read        # help for the read builtin
type echo        # identify echo
type wc          # identify wc
compgen -k       # list Bash keywords
compgen -b       # list Bash builtins
man wc           # manual for the wc program
wc --help        # quick help for wc

Use help for Bash features. Use man or --help for external programs. Use type when you are not sure what a name refers to.

2. Run a command

At a terminal prompt, a command usually has this shape:

command option input

For example:

wc -l /var/log/dpkg.log

This runs wc, asks for a line count with -l, and gives it a file path.

In a script, commands work the same way:

#!/usr/bin/env bash

printf 'Hello, Bash!\n'

printf prints formatted text. It is a good default for script output.

3. Store and use a value

file=/var/log/dpkg.log
printf 'Checking: %s\n' "$file"

4. Give a script an input

Arguments let you pass information when starting a script:

#!/usr/bin/env bash

file=$1
printf 'You gave me: %s\n' "$file"

Run it like this:

bash my_script.sh /var/log/dpkg.log

Useful argument variables:

VariableMeaning
$0Script name
$1First argument
$2Second argument
$#Number of arguments
"$@"All arguments, kept as separate items

Check that an argument was supplied:

if [[ $# -ne 1 ]]; then
    printf 'Usage: %s FILE\n' "$0" >&2
    exit 2
fi

-ne means “not equal.” >&2 sends the message to the error-output stream. exit 2 stops the script with a non-zero status.

5. Make a decision

Use if when the program should do something only when a condition is true:

if [[ -f "$file" ]]; then
    printf 'This is a regular file.\n'
else
    printf 'This is not a regular file.\n'
fi

Read the structure like this:

Add more cases with elif:

if [[ -f "$path" ]]; then
    printf 'File\n'
elif [[ -d "$path" ]]; then
    printf 'Directory\n'
else
    printf 'Neither a regular file nor a directory\n'
fi

Common file tests:

[[ -e "$path" ]]   # something exists at this path
[[ -f "$path" ]]   # regular file
[[ -d "$path" ]]   # directory
[[ -r "$path" ]]   # readable by this user
[[ -w "$path" ]]   # writable by this user
[[ -x "$path" ]]   # executable file, or searchable directory
[[ -s "$path" ]]   # has a size greater than zero

Combine tests:

[[ -f "$file" && -r "$file" ]]  # regular file AND readable
[[ -e "$file" || -L "$file" ]]  # exists OR is a symbolic link
[[ ! -e "$file" ]]               # does NOT exist

In Bash, && means AND, || means OR, and ! means NOT.

6. Repeat a step

Use a for loop to handle several paths:

for file in "$@"; do
    printf 'Checking: %s\n' "$file"
done

The loop takes each argument in turn, puts it in file, and runs the commands between do and done.

Use continue to skip to the next item. Use break to stop the loop.

Read a file one line at a time:

while IFS= read -r line || [[ -n "$line" ]]; do
    printf '%s\n' "$line"
done < "$file"

read -r reads a line without treating backslashes specially. The redirection < "$file" supplies the file as input to the loop.

7. Save the output of a command

Use $(...) to run a command and store its output:

line_count=$(wc -l < "$file")
printf 'Lines: %s\n' "$line_count"

wc -l counts newline characters. A final line without a newline is not counted by this command.

Check whether a command succeeded with if:

if line_count=$(wc -l < "$file"); then
    printf 'Lines: %s\n' "$line_count"
else
    printf 'Could not count lines.\n' >&2
fi

Commands return a status: 0 usually means success; a non-zero number means a problem or a special result.

8. Connect tools

Bash can send one tool's output into another tool with a pipe:

grep -i 'error' "$file" | wc -l

This searches for lines containing “error” and counts the matching lines.

More useful searches:

grep -n 'failed password' "$file"        # show line numbers
grep -i 'error' "$file"                  # ignore letter case
grep -E 'denied|failure|invalid' "$file" # match any listed word

9. Reuse a set of steps

Put a repeated action in a function:

is_readable_file() {
    local path=$1
    [[ -f "$path" && -r "$path" ]]
}

if is_readable_file "$file"; then
    printf 'Ready to read.\n'
fi

local keeps path inside the function. A function returns the status of its last command; here that is the file test.

10. Debug a script

Trace commands as Bash runs them:

set -x       # turn tracing on
# run the commands you are investigating
set +x       # turn tracing off

The trace shows expanded values and commands. It can reveal mistakes such as assigning ile=... and later using $file.

Other useful checks:

type wc                   # what kind of command is this?
printf 'status=%s\n' "$?"  # status from the command just run
bash -x my_script.sh      # run a script with tracing

Use $? immediately; every new command changes it. Traces can expose sensitive paths or arguments, so inspect them before sharing.

11. Complete example: count a log file

#!/usr/bin/env bash

if [[ $# -ne 1 ]]; then
    printf 'Usage: %s LOGFILE\n' "$0" >&2
    exit 2
fi

file=$1

if [[ ! -e "$file" ]]; then
    printf "File doesn't exist: %s\n" "$file" >&2
    exit 1
elif [[ ! -f "$file" ]]; then
    printf 'Not a regular file: %s\n' "$file" >&2
    exit 1
elif [[ ! -r "$file" ]]; then
    printf 'File is not readable: %s\n' "$file" >&2
    exit 1
fi

line_count=$(wc -l < "$file")
printf 'Lines: %s\n' "$line_count"

Try one normal path, one missing path, and one directory. Predict what each run should do before you run it.

Pattern index

I want to...Start with...
Store a valuename=value
Use a value"$name"
Check a conditionif [[ test ]]; then ... fi
Check a file[[ -f "$path" ]]
Repeat over inputsfor item in "$@"; do ... done
Read lineswhile IFS= read -r line; do ... done
Capture outputvalue=$(command)
Search textgrep pattern file
Debug expansionsset -x
Find helphelp name, type name, man command