Skip to content

Instantly share code, notes, and snippets.

@nochmu
Last active November 24, 2018 13:39
Show Gist options
  • Save nochmu/17fb8a31b9eb434b0f8ac49111884439 to your computer and use it in GitHub Desktop.
Save nochmu/17fb8a31b9eb434b0f8ac49111884439 to your computer and use it in GitHub Desktop.
Template for new bash scripts without getopts
#!/usr/bin/env bash
# The following variables are used to describe this script in detail
description="$(basename $0): DESCRIPTION"
version="0.0.1-dev"
author="AUTHOR"
usage_info="
Usage: $(basename $0) ARGS
Arguments:
...
Environment variables:
...
Version: $version
"
############ Development notes ...
# ...
###############################################################################
################################ Describe the environment
# Base directory of this script
basedir="$(dirname "$(readlink -f "$BASH_SOURCE")")"
# .... space for other variables ...
################################ Helper Functions
######## execv
## Print the executed command
## Usage: execv <command line>
## Note:
## Quotations are not printed. Therefore,
## the printed command is not completely safe to be re-executed.
## Set _execv_disabled=true to disable the verbose output
#
function execv
{
prompt="## "
[ "$_execv_disabled" = true ] || echo "${prompt}$@"
"$@"
}
######## raise_error
## Print error message and exit with status code 1
## Usage: raise_error <error message>
#
function raise_error
{
prompt=""
echo "${prompt}$@" 1>&2
exit 1
}
######## show_usage
## Print the usage information
## Usage: show_usage [error message]
## Note:
## If the error message is passed, then the message
## is printed to stderr and the program terminates with 1.
#
function show_usage
{
error_msg="$1"
if [ -z "$error_msg" ]
then
echo "$description"
echo "$usage_info"
exit 0
else
echo "Error: $error_msg" 1>&2
echo "$usage_info" 1>&2
exit 1
fi
}
######## .... space for other functions ...
######## FUNCTION_NAME
## INFO_MESSAGE
## Usage:
#
function print_the_answer
{
the_question="$1"
: ${the_question:?"is empty"}
echo "42"
}
################################ MAIN
#### Without any arguments:
# show the usage information and exit with status code 0 [success]
[ $# -eq 0 ] && show_usage
#### Validate $1: the question
the_question="$1"
[ -n "$the_question" ] || show_usage "The question is missing"
[ $# -eq 1 ] || show_usage "The question has to be passed as a single argument."
# ... space for more validation ...
################ do the stuff
print_the_answer $the_question
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment