Skip to main content

Example Shell Script Format

#!/bin/bash
:

#region Header

# """ A main function script to do script_purpose """

SCRIPT_AUTHOR="Steve T"
SCRIPT_VERSION="0.0.1"
SCRIPT_MAINTAINER="Steve T"
SCRIPT_AUTHOR_EMAIL="steven.v.tuccio@example.com"
SCRIPT_CREATE_DATE=""
SCRIPT_STATUS="Dev"
# shellcheck disable=SC2034
readonly SCRIPT_AUTHOR SCRIPT_VERSION SCRIPT_MAINTAINER SCRIPT_AUTHOR_EMAIL SCRIPT_CREATE_DATE SCRIPT_STATUS

#endregion

#region Imports

#endregion

#region Init

trap finish EXIT ERR # Makes the script run the "finish" function *no matter what* (0 or non-zero exit code)

# Uncomment option to turn on bash option
# set -o errexit # Makes script exit failed if a command fails, instead of continuing with the rest of the script
# set -o nounset # Makes script exit failed if referencing an undefined variable
# set -o pilefail # Makes pipe fail if the first part of the pipe fails, instead of passing the error to the next command
# set -o verbose # Print each command to stdout before executing
# set -o xtrace # Like verbose, but prints expanded command
# set -o restricted # More secure bash scripting. Disables some shell commands to minimize damage script can do. See tldp.org

#endregion

#region Contants

# Bash exit codes
EXITCODE_SUCCESS=0
EXITCODE_ERROR_GENERAL=1
EXITCODE_ERROR_PERMISSION_OR_KEYWORD=2
EXITCODE_ERROR_COMMAND_CANT_EXECUTE=126
EXITCODE_ERROR_COMMAND_NOT_FOUND=127

# shellcheck disable=SC2034
readonly EXITCODE_SUCCESS EXITCODE_ERROR_GENERAL EXITCODE_ERROR_PERMISSION_OR_KEYWORD EXITCODE_ERROR_COMMAND_CANT_EXECUTE EXITCODE_ERROR_COMMAND_NOT_FOUND

#endregion

#region Configurable Variables

#endregion

#region functions

iso_time() {
echo "$(date +%Y-%m-%d)': '$(date +%T)";
}

iso_time_and_zone() {
echo "$(date +%Y-%m-%d) $(date +%T) $(date +%Z)";
}

#endregion

#region Main

main() {
echo 'Start main function at' $(iso_time_and_zone) '- Version: '

echo 'End main function at' $(iso_time_and_zone)
}

finish() {

local result=$?
echo 'Start finish function at' $(iso_time_and_zone)

echo 'End finish function at' $(iso_time_and_zone)
exit

}

main "$@"
exit 0

#endregion

References