Last active
December 25, 2019 07:45
-
-
Save josuecau/cf3858831aae8e4b37cdf3395b23860c to your computer and use it in GitHub Desktop.
Parse bash command options with getopt(1)
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
#!/usr/bin/env bash | |
# “a” and “arga” have optional arguments with default values. | |
# “b” and “argb” have no arguments, acting as sort of a flag. | |
# “c” and “argc” have required arguments. | |
# getopt bin | |
getopt=/usr/local/opt/gnu-getopt/bin/getopt | |
# set an initial value for the flag | |
ARG_B=0 | |
# read the options | |
TEMP=$($getopt -o a::bc: --long arga::,argb,argc: -n 'test.sh' -- "$@") | |
eval set -- "$TEMP" | |
# extract options and their arguments into variables. | |
while true ; do | |
case "$1" in | |
-a|--arga) | |
case "$2" in | |
"") ARG_A='some default value' ; shift 2 ;; | |
*) ARG_A=$2 ; shift 2 ;; | |
esac ;; | |
-b|--argb) ARG_B=1 ; shift ;; | |
-c|--argc) | |
case "$2" in | |
"") shift 2 ;; | |
*) ARG_C=$2 ; shift 2 ;; | |
esac ;; | |
--) shift ; break ;; | |
*) echo "Internal error!" ; exit 1 ;; | |
esac | |
done | |
# do something with the variables -- in this case the lamest possible one :-) | |
echo "ARG_A = $ARG_A" | |
echo "ARG_B = $ARG_B" | |
echo "ARG_C = $ARG_C" |
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
#!/usr/bin/env bash | |
# getopt bin | |
getopt=/usr/local/opt/gnu-getopt/bin/getopt | |
args=$($getopt --options=d --long=delete -- "$@") | |
eval set -- "$args" | |
delete=false | |
while true ; do | |
case "$1" in | |
-d|--delete) | |
delete=true | |
shift | |
;; | |
--) | |
shift | |
break | |
;; | |
*) | |
echo "Error" | |
exit 1 | |
;; | |
esac | |
done | |
if $delete | |
then | |
echo 'Delete is ON' | |
else | |
echo 'Delete is OFF' | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment