Skip to content

Instantly share code, notes, and snippets.

@henhell
Created September 9, 2020 06:45
Show Gist options
  • Save henhell/e496879e48c91a2d05221d3026323886 to your computer and use it in GitHub Desktop.
Save henhell/e496879e48c91a2d05221d3026323886 to your computer and use it in GitHub Desktop.
bash built in getopts example
#!/bin/bash
opt_b=0
opt_c=0
scriptName=`basename $0`
showUsage() { echo "Usage: $scriptName -a <3333|7777> [-b] [-c]" 1>&2; exit 1; }
while getopts ":a:bc" opt; do
case "${opt}" in
a)
opt_a=${OPTARG}
((opt_a == 3333 || opt_a == 7777)) || showUsage
;;
b)
opt_b=1
;;
c)
opt_c="yes"
;;
\?)
echo "Invalid option: $OPTARG" 1>&2
exit 1;
;;
:)
echo "Invalid option: -$OPTARG requires an argument" 1>&2
exit 1;
;;
esac
done
shift $((OPTIND-1))
# if [ -z "${opt_a}" ] || [ -z "${opt_b}" ]; then
if [ -z "${opt_a}" ]; then
showUsage
fi
echo "Results:"
echo "a = ${opt_a}"
echo "b = ${opt_b}"
echo "c = ${opt_c}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment