Build a Reusable Bash Script Template

Summary: Create templates with structure and help menus.


Writing Bash scripts can streamline tasks, but starting from scratch every time is tedious. A template with built-in argument parsing, error handling, and a helpful help menu ensures your scripts are robust, consistent, and easy to maintain. In this post, you'll learn how to create a reusable Bash script template.


Why Use a Script Template?

A good script template:

  • Saves Time: No need to reinvent boilerplate code.
  • Reduces Bugs: Common features (parsing, help menus, error handling) are pre-tested.
  • Improves Consistency: Uniform scripts across different projects.

Let’s build such a template, explain each part, and see how you can reuse it.


The Template: A Solid Foundation

Below is a well-structured Bash script template. No external dependencies, fully portable.

#!/usr/bin/env bash

# =============================================================================
# SCRIPT NAME: script_template.sh
# DESCRIPTION: Brief explanation of what this script does.
#
# USAGE: ./script_template.sh [-h] [-v] [-f <filename>]
#
# OPTIONS:
#   -h            Display this help message and exit
#   -v            Enable verbose mode
#   -f <file>     Specify an input file
#
# EXAMPLES:
#   ./script_template.sh -v -f data.txt
#
# AUTHOR: Your Name
# VERSION: 1.0.0
# ============================================================================

set -euo pipefail

# ---------------------------
# Global Variables
# ---------------------------
VERBOSE=0
INPUT_FILE=""

# ---------------------------
# Functions
# ---------------------------

usage() {
  grep '^#' "$0" | cut -c 3-
  exit 0
}

error_exit() {
  echo "Error: $1" >&2
  exit 1
}

log() {
  if [[ $VERBOSE -eq 1 ]]; then
    echo "[INFO] $*"
  fi
}

# ---------------------------
# Parse Arguments
# ---------------------------

while getopts ":hvf:" opt; do
  case ${opt} in
    h )
      usage
      ;;
    v )
      VERBOSE=1
      ;;
    f )
      INPUT_FILE="$OPTARG"
      ;;
    \? )
      error_exit "Invalid option: -$OPTARG. Use -h for help."
      ;;
    : )
      error_exit "Option -$OPTARG requires an argument."
      ;;
  esac
done
shift $((OPTIND -1))

# ---------------------------
# Main Script
# ---------------------------

main() {
  if [[ -z "$INPUT_FILE" ]]; then
    error_exit "Input file not specified. Use -f <file>."
  fi

  log "Processing file: $INPUT_FILE"
  # Add your main logic here
  # Example:
  # cat "$INPUT_FILE"
}

main "$@"

Key Template Features

1. Shebang and Safe Mode

#!/usr/bin/env bash
set -euo pipefail
  • Ensures portability and that your script aborts on errors or unset variables.

2. Auto-Generated Help

The usage function extracts all help text from the comments at the top of the script using grep. Change or expand these comments, and your help menu automatically updates.

3. Argument Parsing

Using getopts, the script natively supports common flags:

  • -h : Help
  • -v : Verbose logging
  • -f : Input file

Easily extend for more options as needed.

4. Logging and Error Handling

  • The log function prints messages only when verbose mode is enabled.
  • The error_exit function centralizes error reporting and ensures the script halts as soon as an error occurs.

5. Main Execution Flow

Encapsulating your main logic in a main() function improves readability and manageability of larger scripts.


Customizing the Template

  • Add New Options: Extend the getopts case with new flags.
  • Additional Functions: Place utility functions in the Functions section.
  • Expand Usage Block: Add documentation to the comments at the script's top.

Reusing Your Template

  1. Save the template as script_template.sh in a scripts directory.

  2. Copy it whenever you need a new script:

    cp script_template.sh my_new_script.sh
    chmod +x my_new_script.sh
    
  3. Edit the header, adjust options, and insert your logic.


Conclusion

A reusable Bash script template with argument parsing, help menus, error management, and a logical structure is indispensable for productivity and reliability. Start with this foundation, and adapt it to your needs—the benefits scale with each project you tackle!

Happy scripting! 🐧


Further Reading