Skip to content

Commit

Permalink
Implement clean_up_and_exit function
Browse files Browse the repository at this point in the history
  • Loading branch information
Tom Scavo committed Apr 24, 2017
1 parent 663537e commit 9669d74
Showing 1 changed file with 61 additions and 1 deletion.
62 changes: 61 additions & 1 deletion lib/core_lib.sh
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
# limitations under the License.
#######################################################################

#export COMMAND_PATHS=true
_COMPATIBILITY_MODE=true

#######################################################################
Expand Down Expand Up @@ -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
}

0 comments on commit 9669d74

Please sign in to comment.