Created
May 27, 2022 22:01
-
-
Save aqlla/63b4e4451e7faaf4adc69431ab49c4cb to your computer and use it in GitHub Desktop.
Example for shell script getopt with longs because i always forget.
This file contains hidden or 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
# src: https://stackoverflow.com/a/30026641 | |
# credit to @mcoolive | |
# Transform long options to short ones | |
for arg in "$@"; do | |
shift | |
case "$arg" in | |
'--help') set -- "$@" '-h' ;; | |
'--number') set -- "$@" '-n' ;; | |
'--rest') set -- "$@" '-r' ;; | |
'--ws') set -- "$@" '-w' ;; | |
*) set -- "$@" "$arg" ;; | |
esac | |
done | |
# Default behavior | |
number=0; rest=false; ws=false | |
# Parse short options | |
OPTIND=1 | |
while getopts "hn:rw" opt | |
do | |
case "$opt" in | |
'h') print_usage; exit 0 ;; | |
'n') number=$OPTARG ;; | |
'r') rest=true ;; | |
'w') ws=true ;; | |
'?') print_usage >&2; exit 1 ;; | |
esac | |
done | |
shift $(expr $OPTIND - 1) # remove options from positional parameters |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment