mirror of
https://github.com/natelandau/shell-scripting-templates.git
synced 2025-11-10 22:13:48 -05:00
use 4 spaces for indent
This commit is contained in:
@@ -10,23 +10,22 @@ _mainScript_() {
|
|||||||
# Script specific
|
# Script specific
|
||||||
|
|
||||||
# Common
|
# Common
|
||||||
LOGFILE="${HOME}/logs/$(basename "$0")"
|
LOGFILE="${HOME}/logs/$(basename "$0").log"
|
||||||
QUIET=false
|
QUIET=false
|
||||||
LOGLEVEL=ERROR
|
LOGLEVEL=ERROR
|
||||||
VERBOSE=false
|
VERBOSE=false
|
||||||
FORCE=false
|
FORCE=false
|
||||||
DRYRUN=false
|
DRYRUN=false
|
||||||
declare -a args=()
|
declare -a ARGS=()
|
||||||
now=$(LC_ALL=C date +"%m-%d-%Y %r") # Returns: 06-14-2015 10:34:40 PM
|
NOW=$(LC_ALL=C date +"%m-%d-%Y %r") # Returns: 06-14-2015 10:34:40 PM
|
||||||
datestamp=$(LC_ALL=C date +%Y-%m-%d) # Returns: 2015-06-14
|
DATESTAMP=$(LC_ALL=C date +%Y-%m-%d) # Returns: 2015-06-14
|
||||||
hourstamp=$(LC_ALL=C date +%r) # Returns: 10:34:40 PM
|
HOURSTAMP=$(LC_ALL=C date +%r) # Returns: 10:34:40 PM
|
||||||
timestamp=$(LC_ALL=C date +%Y%m%d_%H%M%S) # Returns: 20150614_223440
|
TIMESTAMP=$(LC_ALL=C date +%Y%m%d_%H%M%S) # Returns: 20150614_223440
|
||||||
longdate=$(LC_ALL=C date +"%a, %d %b %Y %H:%M:%S %z") # Returns: Sun, 10 Jan 2016 20:47:53 -0500
|
LONGDATE=$(LC_ALL=C date +"%a, %d %b %Y %H:%M:%S %z") # Returns: Sun, 10 Jan 2016 20:47:53 -0500
|
||||||
gmtdate=$(LC_ALL=C date -u -R | sed 's/\+0000/GMT/') # Returns: Wed, 13 Jan 2016 15:55:29 GMT
|
GMTDATE=$(LC_ALL=C date -u -R | sed 's/\+0000/GMT/') # Returns: Wed, 13 Jan 2016 15:55:29 GMT
|
||||||
|
|
||||||
# ################################## Custom utility functions
|
# ################################## Custom utility functions
|
||||||
|
|
||||||
|
|
||||||
# ################################## Common Functions for script template
|
# ################################## Common Functions for script template
|
||||||
# Colors
|
# Colors
|
||||||
if tput setaf 1 &>/dev/null; then
|
if tput setaf 1 &>/dev/null; then
|
||||||
@@ -40,7 +39,7 @@ _mainScript_() {
|
|||||||
yellow=$(tput setaf 3)
|
yellow=$(tput setaf 3)
|
||||||
blue=$(tput setaf 38)
|
blue=$(tput setaf 38)
|
||||||
underline=$(tput sgr 0 1)
|
underline=$(tput sgr 0 1)
|
||||||
else
|
else
|
||||||
bold="\033[4;37m"
|
bold="\033[4;37m"
|
||||||
white="\033[0;37m"
|
white="\033[0;37m"
|
||||||
reset="\033[0m"
|
reset="\033[0m"
|
||||||
@@ -51,7 +50,7 @@ _mainScript_() {
|
|||||||
yellow="\033[0;33m"
|
yellow="\033[0;33m"
|
||||||
blue="\033[0;34m"
|
blue="\033[0;34m"
|
||||||
underline="\033[4;37m"
|
underline="\033[4;37m"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
_alert_() {
|
_alert_() {
|
||||||
# DESC: Controls all printing of messages to log files and stdout.
|
# DESC: Controls all printing of messages to log files and stdout.
|
||||||
@@ -113,8 +112,8 @@ _alert_() {
|
|||||||
_writeToLog_() {
|
_writeToLog_() {
|
||||||
[[ "${alertType}" == "input" ]] && return 0
|
[[ "${alertType}" == "input" ]] && return 0
|
||||||
[[ "${LOGLEVEL}" =~ (off|OFF|Off) ]] && return 0
|
[[ "${LOGLEVEL}" =~ (off|OFF|Off) ]] && return 0
|
||||||
[ -z "${LOGFILE:-}" ] && fatal "\$LOGFILE must be set"
|
[ -z "${LOGFILE:-}" ] && LOGFILE="$(pwd)/$(basename "$0").log"
|
||||||
[ ! -d "$(dirname "${LOGFILE}")" ] && mkdir -p "$(dirname "${LOGFILE}")"
|
[ ! -d "$(dirname "${LOGFILE}")" ] && command mkdir -p "$(dirname "${LOGFILE}")"
|
||||||
[[ ! -f "${LOGFILE}" ]] && touch "${LOGFILE}"
|
[[ ! -f "${LOGFILE}" ]] && touch "${LOGFILE}"
|
||||||
|
|
||||||
# Don't use colors in logs
|
# Don't use colors in logs
|
||||||
@@ -128,33 +127,33 @@ _alert_() {
|
|||||||
|
|
||||||
# Write specified log level data to logfile
|
# Write specified log level data to logfile
|
||||||
case "${LOGLEVEL:-ERROR}" in
|
case "${LOGLEVEL:-ERROR}" in
|
||||||
ALL|all|All)
|
ALL | all | All)
|
||||||
_writeToLog_
|
_writeToLog_
|
||||||
;;
|
;;
|
||||||
DEBUG|debug|Debug)
|
DEBUG | debug | Debug)
|
||||||
_writeToLog_
|
_writeToLog_
|
||||||
;;
|
;;
|
||||||
INFO|info|Info)
|
INFO | info | Info)
|
||||||
if [[ "${alertType}" =~ ^(die|error|fatal|warning|info|notice|success) ]]; then
|
if [[ "${alertType}" =~ ^(die|error|fatal|warning|info|notice|success) ]]; then
|
||||||
_writeToLog_
|
_writeToLog_
|
||||||
fi
|
fi
|
||||||
;;
|
;;
|
||||||
WARN|warn|Warn)
|
WARN | warn | Warn)
|
||||||
if [[ "${alertType}" =~ ^(die|error|fatal|warning) ]]; then
|
if [[ "${alertType}" =~ ^(die|error|fatal|warning) ]]; then
|
||||||
_writeToLog_
|
_writeToLog_
|
||||||
fi
|
fi
|
||||||
;;
|
;;
|
||||||
ERROR|error|Error)
|
ERROR | error | Error)
|
||||||
if [[ "${alertType}" =~ ^(die|error|fatal) ]]; then
|
if [[ "${alertType}" =~ ^(die|error|fatal) ]]; then
|
||||||
_writeToLog_
|
_writeToLog_
|
||||||
fi
|
fi
|
||||||
;;
|
;;
|
||||||
FATAL|fatal|Fatal)
|
FATAL | fatal | Fatal)
|
||||||
if [[ "${alertType}" =~ ^(die|fatal) ]]; then
|
if [[ "${alertType}" =~ ^(die|fatal) ]]; then
|
||||||
_writeToLog_
|
_writeToLog_
|
||||||
fi
|
fi
|
||||||
;;
|
;;
|
||||||
OFF|off)
|
OFF | off)
|
||||||
return 0
|
return 0
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
@@ -174,8 +173,14 @@ success() { _alert_ success "${1}" "${2:-}"; }
|
|||||||
dryrun() { _alert_ dryrun "${1}" "${2:-}"; }
|
dryrun() { _alert_ dryrun "${1}" "${2:-}"; }
|
||||||
input() { _alert_ input "${1}" "${2:-}"; }
|
input() { _alert_ input "${1}" "${2:-}"; }
|
||||||
header() { _alert_ header "== ${1} ==" "${2:-}"; }
|
header() { _alert_ header "== ${1} ==" "${2:-}"; }
|
||||||
die() { _alert_ fatal "${1}" "${2:-}"; _safeExit_ "1" ; }
|
die() {
|
||||||
fatal() { _alert_ fatal "${1}" "${2:-}"; _safeExit_ "1" ; }
|
_alert_ fatal "${1}" "${2:-}"
|
||||||
|
_safeExit_ "1"
|
||||||
|
}
|
||||||
|
fatal() {
|
||||||
|
_alert_ fatal "${1}" "${2:-}"
|
||||||
|
_safeExit_ "1"
|
||||||
|
}
|
||||||
debug() { _alert_ debug "${1}" "${2:-}"; }
|
debug() { _alert_ debug "${1}" "${2:-}"; }
|
||||||
verbose() { _alert_ debug "${1}" "${2:-}"; }
|
verbose() { _alert_ debug "${1}" "${2:-}"; }
|
||||||
|
|
||||||
@@ -184,19 +189,21 @@ _safeExit_() {
|
|||||||
# ARGS: $1 (optional) - Exit code (defaults to 0)
|
# ARGS: $1 (optional) - Exit code (defaults to 0)
|
||||||
# OUTS: None
|
# OUTS: None
|
||||||
|
|
||||||
if [[ -d "${script_lock:-}" ]]; then
|
if [[ -d "${SCRIPT_LOCK:-}" ]]; then
|
||||||
if command rm -rf "${script_lock}"; then
|
if command rm -rf "${SCRIPT_LOCK}"; then
|
||||||
debug "Removing script lock"
|
debug "Removing script lock"
|
||||||
else
|
else
|
||||||
warning "Script lock could not be removed. Try manually deleting ${tan}'${lock_dir}'${red}"
|
warning "Script lock could not be removed. Try manually deleting ${tan}'${LOCK_DIR}'${red}"
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [[ -n "${tmpDir:-}" && -d "${tmpDir:-}" ]]; then
|
if [[ -n "${TMP_DIR:-}" && -d "${TMP_DIR:-}" ]]; then
|
||||||
if [[ ${1:-} == 1 && -n "$(ls "${tmpDir}")" ]]; then
|
if [[ ${1:-} == 1 && -n "$(ls "${TMP_DIR}")" ]]; then
|
||||||
command rm -r "${tmpDir}"
|
# Do something here to save TMP_DIR on a non-zero script exit for debugging
|
||||||
|
command rm -r "${TMP_DIR}"
|
||||||
|
debug "Removing temp directory"
|
||||||
else
|
else
|
||||||
command rm -r "${tmpDir}"
|
command rm -r "${TMP_DIR}"
|
||||||
debug "Removing temp directory"
|
debug "Removing temp directory"
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
@@ -225,9 +232,9 @@ _trapCleanup_() {
|
|||||||
funcstack="'$(echo "$funcstack" | sed -E 's/ / < /g')'"
|
funcstack="'$(echo "$funcstack" | sed -E 's/ / < /g')'"
|
||||||
|
|
||||||
if [[ "${script##*/}" == "${sourced##*/}" ]]; then
|
if [[ "${script##*/}" == "${sourced##*/}" ]]; then
|
||||||
fatal "${7:-} command: '$command' (line: $line) [func: $(_functionStack_)]"
|
fatal "${7:-} command: '${command}' (line: ${line}) [func: $(_functionStack_)]"
|
||||||
else
|
else
|
||||||
fatal "${7:-} command: '$command' (func: ${funcstack} called at line $linecallfunc of '${script##*/}') (line: $line of '${sourced##*/}') "
|
fatal "${7:-} command: '${command}' (func: ${funcstack} called at line ${linecallfunc} of '${script##*/}') (line: $line of '${sourced##*/}') "
|
||||||
fi
|
fi
|
||||||
|
|
||||||
_safeExit_ "1"
|
_safeExit_ "1"
|
||||||
@@ -236,43 +243,43 @@ _trapCleanup_() {
|
|||||||
_makeTempDir_() {
|
_makeTempDir_() {
|
||||||
# DESC: Creates a temp directory to house temporary files
|
# DESC: Creates a temp directory to house temporary files
|
||||||
# ARGS: $1 (Optional) - First characters/word of directory name
|
# ARGS: $1 (Optional) - First characters/word of directory name
|
||||||
# OUTS: $tmpDir - Temporary directory
|
# OUTS: $TMP_DIR - Temporary directory
|
||||||
# USAGE: _makeTempDir_ "$(basename "$0")"
|
# USAGE: _makeTempDir_ "$(basename "$0")"
|
||||||
|
|
||||||
[ -d "${tmpDir:-}" ] && return 0
|
[ -d "${TMP_DIR:-}" ] && return 0
|
||||||
|
|
||||||
if [ -n "${1:-}" ]; then
|
if [ -n "${1:-}" ]; then
|
||||||
tmpDir="${TMPDIR:-/tmp/}${1}.$RANDOM.$RANDOM.$$"
|
TMP_DIR="${TMPDIR:-/tmp/}${1}.$RANDOM.$RANDOM.$$"
|
||||||
else
|
else
|
||||||
tmpDir="${TMPDIR:-/tmp/}$(basename "$0").$RANDOM.$RANDOM.$RANDOM.$$"
|
TMP_DIR="${TMPDIR:-/tmp/}$(basename "$0").$RANDOM.$RANDOM.$RANDOM.$$"
|
||||||
fi
|
fi
|
||||||
(umask 077 && mkdir "${tmpDir}") || {
|
(umask 077 && mkdir "${TMP_DIR}") || {
|
||||||
fatal "Could not create temporary directory! Exiting."
|
fatal "Could not create temporary directory! Exiting."
|
||||||
}
|
}
|
||||||
debug "\$tmpDir=$tmpDir"
|
debug "\$TMP_DIR=${TMP_DIR}"
|
||||||
}
|
}
|
||||||
|
|
||||||
_acquireScriptLock_() {
|
_acquireScriptLock_() {
|
||||||
# DESC: Acquire script lock
|
# DESC: Acquire script lock
|
||||||
# ARGS: $1 (optional) - Scope of script execution lock (system or user)
|
# ARGS: $1 (optional) - Scope of script execution lock (system or user)
|
||||||
# OUTS: $script_lock - Path to the directory indicating we have the script lock
|
# OUTS: $SCRIPT_LOCK - Path to the directory indicating we have the script lock
|
||||||
# NOTE: This lock implementation is extremely simple but should be reliable
|
# NOTE: This lock implementation is extremely simple but should be reliable
|
||||||
# across all platforms. It does *not* support locking a script with
|
# across all platforms. It does *not* support locking a script with
|
||||||
# symlinks or multiple hardlinks as there's no portable way of doing so.
|
# symlinks or multiple hardlinks as there's no portable way of doing so.
|
||||||
# If the lock was acquired it's automatically released in _safeExit_()
|
# If the lock was acquired it's automatically released in _safeExit_()
|
||||||
|
|
||||||
local lock_dir
|
local LOCK_DIR
|
||||||
if [[ ${1:-} == 'system' ]]; then
|
if [[ ${1:-} == 'system' ]]; then
|
||||||
lock_dir="${TMPDIR:-/tmp/}$(basename "$0").lock"
|
LOCK_DIR="${TMPDIR:-/tmp/}$(basename "$0").lock"
|
||||||
else
|
else
|
||||||
lock_dir="${TMPDIR:-/tmp/}$(basename "$0").$UID.lock"
|
LOCK_DIR="${TMPDIR:-/tmp/}$(basename "$0").$UID.lock"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if command mkdir "${lock_dir}" 2>/dev/null; then
|
if command mkdir "${LOCK_DIR}" 2>/dev/null; then
|
||||||
readonly script_lock="${lock_dir}"
|
readonly SCRIPT_LOCK="${LOCK_DIR}"
|
||||||
debug "Acquired script lock: ${tan}${script_lock}${purple}"
|
debug "Acquired script lock: ${tan}${SCRIPT_LOCK}${purple}"
|
||||||
else
|
else
|
||||||
error "Unable to acquire script lock: ${tan}${lock_dir}${red}"
|
error "Unable to acquire script lock: ${tan}${LOCK_DIR}${red}"
|
||||||
fatal "If you trust the script isn't running, delete the lock dir"
|
fatal "If you trust the script isn't running, delete the lock dir"
|
||||||
fi
|
fi
|
||||||
}
|
}
|
||||||
@@ -285,7 +292,7 @@ _functionStack_() {
|
|||||||
local _i
|
local _i
|
||||||
funcStackResponse=()
|
funcStackResponse=()
|
||||||
for ((_i = 1; _i < ${#BASH_SOURCE[@]}; _i++)); do
|
for ((_i = 1; _i < ${#BASH_SOURCE[@]}; _i++)); do
|
||||||
case "${FUNCNAME[$_i]}" in "_alert_" | "_trapCleanup_" | fatal | error | warning | verbose | debug | die) continue ;; esac
|
case "${FUNCNAME[$_i]}" in "_alert_" | "_trapCleanup_" | fatal | error | warning | notice | info | verbose | debug | dryrun | header | success | die) continue ;; esac
|
||||||
funcStackResponse+=("${FUNCNAME[$_i]}:$(basename ${BASH_SOURCE[$_i]}):${BASH_LINENO[$_i - 1]}")
|
funcStackResponse+=("${FUNCNAME[$_i]}:$(basename ${BASH_SOURCE[$_i]}):${BASH_LINENO[$_i - 1]}")
|
||||||
done
|
done
|
||||||
printf "( "
|
printf "( "
|
||||||
@@ -330,15 +337,18 @@ _parseOptions_() {
|
|||||||
# Read the options and set stuff
|
# Read the options and set stuff
|
||||||
while [[ ${1:-} == -?* ]]; do
|
while [[ ${1:-} == -?* ]]; do
|
||||||
case $1 in
|
case $1 in
|
||||||
|
# Custom options
|
||||||
|
|
||||||
|
# Common options
|
||||||
-h | --help)
|
-h | --help)
|
||||||
_usage_ >&2
|
_usage_ >&2
|
||||||
_safeExit_
|
_safeExit_
|
||||||
;;
|
;;
|
||||||
-l | --loglevel)
|
--loglevel)
|
||||||
shift
|
shift
|
||||||
LOGLEVEL=${1}
|
LOGLEVEL=${1}
|
||||||
;;
|
;;
|
||||||
-L | --logfile)
|
--logfile)
|
||||||
shift
|
shift
|
||||||
LOGFILE="${1}"
|
LOGFILE="${1}"
|
||||||
;;
|
;;
|
||||||
@@ -354,7 +364,7 @@ _parseOptions_() {
|
|||||||
esac
|
esac
|
||||||
shift
|
shift
|
||||||
done
|
done
|
||||||
args+=("$@") # Store the remaining user input as arguments.
|
ARGS+=("$@") # Store the remaining user input as arguments.
|
||||||
}
|
}
|
||||||
|
|
||||||
_usage_() {
|
_usage_() {
|
||||||
@@ -366,20 +376,22 @@ _usage_() {
|
|||||||
|
|
||||||
${bold}Options:${reset}
|
${bold}Options:${reset}
|
||||||
-h, --help Display this help and exit
|
-h, --help Display this help and exit
|
||||||
-l, --loglevel One of: FATAL, ERROR, WARN, INFO, DEBUG, ALL, OFF (Default is 'ERROR')
|
--loglevel [LEVEL] One of: FATAL, ERROR, WARN, INFO, DEBUG, ALL, OFF (Default is 'ERROR')
|
||||||
|
--logfile [FILE] Full PATH to logfile. (Default is '${HOME}/logs/$(basename "$0").log')
|
||||||
$ $(basename "$0") --loglevel 'WARN'
|
|
||||||
|
|
||||||
-L, --logfile Full PATH to logfile. (Default is '${HOME}/logs/$(basename "$0")')
|
|
||||||
|
|
||||||
-n, --dryrun Non-destructive. Makes no permanent changes.
|
-n, --dryrun Non-destructive. Makes no permanent changes.
|
||||||
-q, --quiet Quiet (no output)
|
-q, --quiet Quiet (no output)
|
||||||
-v, --verbose Output more information. (Items echoed to 'verbose')
|
-v, --verbose Output more information. (Items echoed to 'verbose')
|
||||||
--force Skip all user interaction. Implied 'Yes' to all actions.
|
--force Skip all user interaction. Implied 'Yes' to all actions.
|
||||||
|
|
||||||
|
${bold}Example Usage:${reset}
|
||||||
|
|
||||||
|
$ $(basename "$0") -vn --logfile "/path/to/file.log" --loglevel 'WARN'
|
||||||
EOF
|
EOF
|
||||||
}
|
}
|
||||||
|
|
||||||
# Initialize and run the script
|
# ################################## INITIALIZE AND RUN THE SCRIPT
|
||||||
|
# (Comment or uncomment the lines below to customize script behavior)
|
||||||
|
|
||||||
trap '_trapCleanup_ ${LINENO} ${BASH_LINENO} "${BASH_COMMAND}" "${FUNCNAME[*]}" "${0}" "${BASH_SOURCE[0]}"' \
|
trap '_trapCleanup_ ${LINENO} ${BASH_LINENO} "${BASH_COMMAND}" "${FUNCNAME[*]}" "${0}" "${BASH_SOURCE[0]}"' \
|
||||||
EXIT INT TERM SIGINT SIGQUIT
|
EXIT INT TERM SIGINT SIGQUIT
|
||||||
set -o errtrace # Trap errors in subshells and functions
|
set -o errtrace # Trap errors in subshells and functions
|
||||||
@@ -391,7 +403,7 @@ IFS=$' \n\t' # Set IFS to preferred implementation
|
|||||||
set -o nounset # Disallow expansion of unset variables
|
set -o nounset # Disallow expansion of unset variables
|
||||||
# [[ $# -eq 0 ]] && _parseOptions_ "-h" # Force arguments when invoking the script
|
# [[ $# -eq 0 ]] && _parseOptions_ "-h" # Force arguments when invoking the script
|
||||||
_parseOptions_ "$@" # Parse arguments passed to script
|
_parseOptions_ "$@" # Parse arguments passed to script
|
||||||
# _makeTempDir_ "$(basename "$0")" # Create a temp directory '$tmpDir'
|
# _makeTempDir_ "$(basename "$0")" # Create a temp directory '$TMP_DIR'
|
||||||
# _acquireScriptLock_ # Acquire script lock
|
# _acquireScriptLock_ # Acquire script lock
|
||||||
_mainScript_ # Run the main logic script
|
_mainScript_ # Run the main logic script
|
||||||
_safeExit_ # Exit cleanly
|
_safeExit_ # Exit cleanly
|
||||||
|
|||||||
Reference in New Issue
Block a user