Last active
October 24, 2021 07:28
-
-
Save runswithd6s/11404707 to your computer and use it in GitHub Desktop.
BASH Script Boilerplate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
################################################################################ | |
# Boilerplate Shell Script with getopt parsing | |
# | |
# This script is released to the Public Domain by Chad Walstrom | |
# Chad Walstrom <[email protected]>. | |
################################################################################ | |
NOACT=0 | |
NAME=$(basename $0|sed 's/\(\..*\)$//') | |
VERSION="0.1" | |
# Set the defaults | |
: ${VERBOSE:=0} | |
: ${LOGFILE:="${NAME}.log"} | |
: ${CONF_FILE:="${NAME}.conf"} | |
: ${NOACT:=0} | |
HOSTNAME=`hostname -s` | |
function version() { | |
cat <<EOF >&2 | |
$NAME - $VERSION | |
EOF | |
} | |
function copyright(){ | |
version | |
cat << EOCOPYRIGHT >&2 | |
Copyright (C) YYYY AUTHOR | |
ADD TERMS HERE | |
EOCOPYRIGHT | |
} | |
function usage() { | |
cat <<EOUSAGE >&2 | |
[$@] | |
Usage: $NAME [OPTIONS] ARGS... | |
Simple description on how to use this script... | |
OPTION DESCRIPTION | |
========== ================================================================== | |
-c FILE Configuration file path (Default: ${CONF_FILE}) | |
-l FILE Log file path (Default: ${LOG_FILE}) | |
-n No Act (and Verbose) | |
-q Quiet | |
-v Verbose (can specify multiple times) | |
-V Version | |
-w Copyright and Warranty information | |
-h This text | |
EOUSAGE | |
} | |
# Log to the logfile | |
function log() { | |
echo "$(date +%Y%m%d.%H%M%S) [$NAME:$$] $@" >> ${LOGFILE} | |
} | |
# Echo the message if verbose and return 1, else return 0 | |
function verbose() { | |
log $@ | |
if [[ ${VERBOSE} -gt 0 ]] ; then | |
echo $@ >&2 | |
return 1 | |
fi | |
return 0 | |
} | |
################################################################################# | |
# Main body | |
# Parse options | |
while getopts ":u:p:c:hnqw" opt; do | |
case $opt in | |
c) CONF_FILE=${OPTARG} ;; | |
h) usage "Help Requested" ; exit 0;; | |
n) NOACT=1; VERBOSE=1 ;; | |
q) VERBOSE=0 ;; | |
v) VERBOSE=$(($VERBOSE+1)) ;; | |
V) version ; exit 0;; | |
w) copyright; exit 0;; | |
:) usage "Option -${OPTARG} requires an argument." ; exit 1 ;; | |
\?) usage "Invalid option -${OPTARG}" ; exit 1;; | |
esac | |
done | |
shift $((OPTIND-1)) | |
# Read in the config file | |
if [[ -f ${CONF_FILE} ]] ; then | |
. ${CONF_FILE} | |
fi | |
# Customize to required arguments | |
if [[ $# -lt 2 ]] ; then | |
usage "You must specify two arguments." | |
exit 2 | |
fi | |
# Validate your arguments | |
verbose "Validating arguments: $@" | |
# Do stuff | |
# EOF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment