Improve your bash scripts with this boilerplate template

snippets bash

First up - here’s the template. Continue reading below for an explanation of each component.

Unofficial Strict Mode

set -euo pipefail

There’s a few things going on here -

Logging Helpers

This template provides helpers for displaying log messages at various levels. These levels provide more context for users of the script. fatal has special behavior where it will exit the script with after displaying the message.


cleanup() {
  info "... cleaned up"
trap cleanup EXIT

This pattern ensures the cleanup function is called when the script terminates. This allows you to clean up temporary files, restart services, or provide feedback to the user.

Built-in Documentation

Calling the script with --help flag triggers the help text to display. Fill out the comment block at the top to describe how to use your script.

./ --help

Usage:        ./ [user] [group]
Description:  Adds a user to a group. Requires root.
Examples:     ./ apache www-data
  --help: Display this help message

More Best Practices

This template was adapted from this excellent blog post Shell Scripts Matter. I highly recommend having a read of this article to get more tips on shell script best practices.