Bash Shell Script Template

· [b]log.mlots


A minimal Bash shell script template and structure I find useful, modified slightly, from Jason Cannon's book "Shell Scripting".

 1#!/usr/bin/env bash
 2#
 3# <Replace with the purpose or description of of this shell script.>
 4#
 5
 6GLOBAL_VAR1="one"
 7GLOBAL_VAR2="two"
 8
 9function function_one() {
10    local LOCAL_VAR1="one"
11    # <Replace with function code.>
12}
13
14# Main body of shell script starts here.
15#
16# <Replace with the main commands of your shell script.>
17#
18
19# Exit with an explicit exit status.
20exit 0

According to Cannon, this should be the basic structure of a shell script:

  1. Shebang - decalares the interpreter
  2. Comment - summarize what the script does
  3. Global Variables - if you need to use global variables, declare them at the top of the script
  4. Functions - declare and group your functions together before the main portion of your script, use the local keyword for variables inside a function
  5. Main Script - here is the main portion of your script calling any functions as needed
  6. Exit Status - cleanly end your script with an exit 0 line

Where I differ from Cannon is in the shebang line. Cannon uses #!/bin/bash, which is fine in most cases, but I prefer to use the advice of youtuber Dave Eddy. Bash is not always located at /bin/bash on every system, so instead use #!/usr/bin/env bash to allow finding the location of bash using the $PATH environment variable.

Footnotes #