From 9669d74de17713d4095eb17c12ace2006633a3cf Mon Sep 17 00:00:00 2001 From: Tom Scavo Date: Mon, 24 Apr 2017 14:51:27 -0400 Subject: [PATCH] Implement clean_up_and_exit function --- lib/core_lib.sh | 62 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 61 insertions(+), 1 deletion(-) diff --git a/lib/core_lib.sh b/lib/core_lib.sh index 90d3896..2c18d6c 100755 --- a/lib/core_lib.sh +++ b/lib/core_lib.sh @@ -16,7 +16,6 @@ # limitations under the License. ####################################################################### -#export COMMAND_PATHS=true _COMPATIBILITY_MODE=true ####################################################################### @@ -206,3 +205,64 @@ print_log_message () { # prepend timestamp to the log message printf "%s %s\n" "$tstamp" "$log_message" >> "$log_file" } + +####################################################################### +# Clean up and exit the script. +# +# Usage: +# $ clean_up_and_exit [-d DIR_TO_BE_DELETED] EXIT_CODE +# +# This script is compatible with Mac OS and GNU/Linux. +####################################################################### + +clean_up_and_exit () { + + local unwanted_dir + local exit_code + + local opt + local OPTARG + local OPTIND + while getopts ":d:" opt; do + case $opt in + d) + unwanted_dir="$OPTARG" + ;; + \?) + echo "ERROR: $FUNCNAME: Unrecognized option: -$OPTARG" >&2 + return 2 + ;; + :) + echo "ERROR: $FUNCNAME: Option -$OPTARG requires an argument" >&2 + return 2 + ;; + esac + done + + # determine the exit code + shift $(( OPTIND - 1 )) + if [ $# -ne 1 ]; then + echo "ERROR: $FUNCNAME: wrong number of arguments: $# (1 required)" >&2 + return 2 + fi + exit_code="$1" + if [ ! "$exit_code" -gt 0 ] ; then + echo "ERROR: $FUNCNAME: illegal exit code: $exit_code" >&2 + return 2 + fi + + if [ -n "$unwanted_dir" ]; then + if [ ! -d "$unwanted_dir" ]; then + echo "ERROR: $FUNCNAME: directory does not exist: $unwanted_dir" >&2 + return 2 + fi + + # remove the unwanted directory (!) + /bin/rm -rf "$unwanted_dir" + if [ $? -ne 0 ]; then + echo "ERROR: $FUNCNAME failed to remove dir: $unwanted_dir" >&2 + fi + fi + + exit $exit_code +}