Skip to content

Instantly share code, notes, and snippets.

@bluegraybox
Created May 29, 2019 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluegraybox/11980965fa04e611353ebee3ead1c2e9 to your computer and use it in GitHub Desktop.
Save bluegraybox/11980965fa04e611353ebee3ead1c2e9 to your computer and use it in GitHub Desktop.
# For reference: 1>&2 redirects output to stderr
# This script should only be sourced by other scripts
if [[ "$0" != '-bash' ]] ; then
echo 'WARNING: functions.sh should be sourced, not executed' 1>&2
fi
# Check for an error, and optionally display a message
function check_ok() {
local errcode=$?
if [[ "$errcode" -ne 0 ]] ; then
if [ -n "$1" ] ; then
echo "$1" 1>&2
fi
return $errcode
else
return 0
fi
}
# Check that a file exists, and optionally display a message
function check_exists() {
if [ -z "$1" ] ; then
echo 'Usage: check_exists <filepath> [<error message>]' 1>&2
return 1
fi
local filename=$1
if [[ ! -f "$filename" ]] ; then
if [ -n "$2" ] ; then
echo "$2" 1>&2
fi
return 1
else
return 0
fi
}
function _test_check_ok_inner() {
ls /invalid/path/bogus-filename.ext 2> /dev/null
check_ok "check_ok test passed" || return $?
echo "check_ok test failed" 1>&2
}
function _test_check_exists() {
check_exists /invalid/path/bogus-filename.ext "check_exists test passed"
check_ok "check_exists returned correct error code" || return $?
echo "check_exists returned wrong error code" 1>&2
}
function _test_check_exists_bad_invocation() {
# This fails because
export err_code=0
local err_msg=$(check_exists 2>&1 ; err_code=$?)
echo "err_code=$err_code"
echo "err_msg=$err_msg"
echo "\$?=$? when capturing output"
check_ok "check_exists returned correct error code" || return $?
echo "check_exists returned wrong error code" 1>&2
}
function test_functions() {
_test_check_ok_inner
_test_check_exists
_test_check_exists_bad_invocation
}
@bluegraybox
Copy link
Author

Work in progress

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment