Structure and style: main functions and shfmt

Intermediate · 3 min

Lay out a script with functions and a main, guard it so it can be sourced for tests, and let shfmt and ShellCheck settle formatting. Run on shfmt 3.14.

Before thisFunctions, arguments and scopeStrict mode - set -e, -u and pipefailDebugging with set -x and ShellCheckPortability: POSIX sh and Bash

Tom on the Internet · 3 min

Structure and style: main functions and shfmt

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Tom on the InternetReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A script that grows past a few lines reads best as small functions plus a main function that runs them, called at the bottom with main "$@".
  • Guarding the call with [[ ${BASH_SOURCE[0]} == "$0" ]] lets another script, or a test, source the file and use its functions without running it.
  • set -e does not catch a failure inside echo "$(cmd)", because the substitution's status is lost. Assign first (n=$(cmd)), then use the variable.
  • shfmt formats shell code the way gofmt formats Go: shfmt -d shows the changes, -w applies them, -l lists files, and -i 2 chooses two-space indents. Agreeing on a formatter ends style arguments.
  • shfmt only changes layout. ShellCheck finds bugs. Run both, and in CI use shfmt -d and shellcheck, which fail when something is off.

Why layout matters more in shell

Scripts start as five lines and are still running ten years later. Shell makes it easy to let them rot: everything is global by default, there are no modules, and a typo is only found when that line runs. The remedy is dull and effective. Put each idea in a named function, put the entry point in one place, and let a tool settle the formatting.

I tested everything here with shfmt 3.14.1, ShellCheck 0.11 and Bash 5.3, on a script that counts HTTP 500s in access logs.

Before: loose code

#!/usr/bin/env bash
count_errors(){
local file=$1
if [ -f "$file" ];then
grep -c ' 500 ' "$file"
else
echo "no such file: $file" >&2
return 1
fi
}
for f in "$@"
do
  echo "$f: $(count_errors "$f")"
done

It works, and it is a little hard to read. It also has a hidden problem, which comes up below.

shfmt: no more style debates

shfmt rewrites shell source into one canonical layout. -l lists files that would change, -d shows the diff, -w rewrites in place. The default indent is a tab, and -i 2 asks for two spaces:

$ shfmt -d messy.sh
 #!/usr/bin/env bash
-count_errors(){
-local file=$1
-if [ -f "$file" ];then
...
+count_errors() {
+	local file=$1
+	if [ -f "$file" ]; then

With -i 2, the whole file came out indented and spaced:

$ shfmt -i 2 messy.sh
#!/usr/bin/env bash
count_errors() {
  local file=$1
  if [ -f "$file" ]; then
    grep -c ' 500 ' "$file"
  ...
for f in "$@"; do
  echo "$f: $(count_errors "$f")"
done

shfmt -l exits 1 when something would change, and shfmt -d exits 1 too, so either works as a CI gate. After -w the file was clean (-l printed nothing, exit 0). Other options exist: -ci indents case bodies, -bn lets && and | start a line, and -s simplifies code. It reads .editorconfig, which I confirmed by setting a two-space indent there and getting two-space output without -i. It only changes layout, never behaviour. Finding mistakes is ShellCheck’s job, and the two make a pair.

After: functions and a main

#!/usr/bin/env bash
# Count HTTP 500s in one or more access logs.
set -euo pipefail

count_errors() {
  local file=$1
  if [[ ! -f $file ]]; then
    echo "no such file: $file" >&2
    return 1
  fi
  grep -c ' 500 ' "$file" || true
}

main() {
  local f n
  for f in "$@"; do
    n=$(count_errors "$f")
    echo "$f: $n"
  done
}

if [[ ${BASH_SOURCE[0]} == "$0" ]]; then
  main "$@"
fi

Several choices are worth explaining.

  • Functions with local. Variables stay inside, which is what function scope is for.
  • main plus one call. The flow reads from the bottom. main "$@" passes the arguments through, quoted so they stay separate.
  • The guard. ${BASH_SOURCE[0]} is this file’s name, and $0 is the name of what was run. They match only when you execute the file directly. When another script sources it, they differ, so main does not run. I confirmed it:
$ bash -c 'source ./tidy.sh; echo "sourced ok"; count_errors fx/logs/access.log'
sourced ok
24

The functions loaded and main stayed quiet. That is what lets a test file call count_errors directly.

  • || true after grep -c. grep exits 1 when it finds no match, which under set -e would kill the script, even though 0 is a perfectly good count. I checked: grep -c zzz file printed 0 and exited 1.

This version passed shfmt -i 2 -d and ShellCheck. Note it did not at first: my first draft used [[ ... ]] || { echo ...; return 1; } on one line, and shfmt rewrote it across four lines.

The set -e trap I hit

The first version of main had a single line, echo "$f: $(count_errors "$f")". With a missing file it printed the error, then an empty count, and exited 0, even under set -e:

nope: 
fx/logs/access.log: 24
exit=0

The failure of count_errors was inside a command substitution, and the exit status that set -e sees is that of echo, which succeeded. Assigning first, as n=$(count_errors "$f"), makes the failure the status of the assignment:

$ bash tidy.sh nope fx/logs/access.log; echo "exit=$?"
no such file: nope
exit=1

The script stopped at the bad file with a nonzero status. The strict mode lesson lists more places where set -e is quieter than it seems.

What to adopt

A short checklist that held up in this test: a shebang, a one-line comment saying what the script does, set -euo pipefail if you want strict mode, small functions with local variables, main "$@" behind the guard, and shfmt plus shellcheck in CI or a pre-commit hook (the Git lessons cover hooks). Errors belong on standard error with a nonzero exit, which the logging lesson covers next but one.

About the video

“Write Better Bash Scripts! Use ShellCheck and shfmt” is a 3-minute 16-second video from Tom on the Internet, published February 2022. The description is only links, with no chapters, and I could not read a transcript. From the title it covers ShellCheck and shfmt, so the main function and guard pattern above are probably beyond it. I looked for a video that demonstrably covers main, the source guard and shfmt together and did not find one, so I kept this as the only candidate that names shfmt. It is in English. Two longer videos are linked under deeper: Michael Knapp’s conference talk “Maintainable Bash Scripting” (Capital One, 42 minutes), whose chapters cover simplifications, variable scope, order of operations, returning values and writing effective functions, and Better Stack’s summary of the Google shell style guide.

Where this fits

A script that is laid out well still needs somewhere safe to put scratch files and a way to write output without leaving half a file behind: safe temporary files and atomic writes.

Check yourself

  1. 01Why put the work in a main function and call it as main "$@"?

    Top-level code runs on source, so a script of loose commands cannot be reused. A main function makes the script's flow explicit and passes its arguments through unchanged.

  2. 02What does the [[ ${BASH_SOURCE[0]} == "$0" ]] check do?

    It is true only when the file is executed directly. When it is sourced, $0 is the caller, so main does not run and the functions can be tested.

  3. 03Under set -e a function fails inside echo "$f: $(count_errors "$f")" and the script carries on. How do you fix it?

    Assign the result in its own statement, n=$(count_errors "$f"), and then echo it. A failing assignment does trigger set -e, and the echo's own status no longer hides it.

  4. 04How do you make shfmt fail a CI job when a file is unformatted?

    Run shfmt -d (or -l) over the files. Both exit nonzero when a file would change, and -d prints the diff.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark