[b]log.mlots.page

Bash Shell Script Template

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

#!/usr/bin/env bash
#
# <Replace with the purpose or description of of this shell script.>
#

GLOBAL_VAR1="one"
GLOBAL_VAR2="two"

function function_one() {
    local LOCAL_VAR1="one"
    # <Replace with function code.>
}

# Main body of shell script starts here.
#
# <Replace with the main commands of your shell script.>
#

# Exit with an explicit exit status.
exit 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

  • Cannon, Jason. 2015. Shell Scripting. CreateSpace. https://www.linuxtrainingacademy.com/
  • "Bash Style Guide". Dave Eddy. 2026. Ysap.sh. 2026. https://style.ysap.sh/.
  • You Suck at Programming. 2025. “Why I Don’t Use #!/Bin/Bash - Shebangs Explained!” YouTube. August 30, 2025. https://www.youtube.com/watch?v=aoHMiCzqCNw.