Skip to content

Instantly share code, notes, and snippets.

@aqlla
Created May 27, 2022 22:01
Show Gist options
  • Save aqlla/63b4e4451e7faaf4adc69431ab49c4cb to your computer and use it in GitHub Desktop.
Save aqlla/63b4e4451e7faaf4adc69431ab49c4cb to your computer and use it in GitHub Desktop.
Example for shell script getopt with longs because i always forget.
# 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