Last active
November 27, 2017 22:56
-
-
Save norpol/9a07ee85ba54fb6e7d7fc9e3c77ecc84 to your computer and use it in GitHub Desktop.
getopts example/testcase/discussion
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
#!/bin/sh | |
set -ue | |
error() { | |
echo "${*:-Something failed}" | |
exit 1 | |
} | |
check() { | |
arguments="${*}" | |
command="${arguments#*? }" | |
set +e | |
message="$(eval "${command}" 2>&1)" | |
return_value="$?" | |
set -e | |
foo="${arguments%% ?*}" | |
fail="${foo#?*=}" | |
if [ "fail" = "${fail}" ]; then | |
if [ "${return_value}" -eq "0" ]; then | |
echo "Expected to fail, success(${return_value}): ${command}, message: ${message:-Empty Message}" | |
fi | |
elif [ "${return_value}" -gt "0" ]; then | |
echo "Expected success, received fail(${return_value}): ${command}, message: ${message:-Empty Message}" | |
fi | |
} | |
opts() { | |
arg= | |
optscmd="getopts :abc: arg" | |
${optscmd} || error "Nothing given" | |
while ${optscmd}; do | |
case "${arg}" in | |
a) export AV="A" | |
;; | |
b) export BV="B" | |
;; | |
c) export CV="${OPTARG}" | |
;; | |
?) error "Unknown arg: ${OPTARG}" | |
esac | |
done | |
[ -n "${CV}" ] || error "-c option missing" | |
} | |
check c=fail false # test my tests | |
check c=succ true # test my tests | |
check c=succ opts -a -b -c SOMETHING | |
check c=succ opts -b -c SOMETHING # a is optional | |
check c=fail opts # nothing, should "fail" (e.g. print help page) | |
check c=fail opts -b -c # missing <data> for -c | |
check c=fail opts -a -b # missing mandatory/required -c <data> | |
check c=fail opts -a -b -c SOMETHING -d # undefined arg -d |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment