Skip to content

Instantly share code, notes, and snippets.

@konsolebox
Created September 29, 2023 21:39
Show Gist options
  • Select an option

  • Save konsolebox/985da7c3442ce5c5c792928f65c3a7cd to your computer and use it in GitHub Desktop.

Select an option

Save konsolebox/985da7c3442ce5c5c792928f65c3a7cd to your computer and use it in GitHub Desktop.
function get_opt_and_optarg_gnu {
local optional=false
if [[ $1 == @optional ]]; then
optional=true
shift
fi
OPT=$1 OPTARG= OPTSHIFT=0
if [[ $1 == -[!-]* && ${optional} == true ]]; then
OPT=${1:0:2} OPTARG=${1:2}
[[ ${OPTARG} ]] || return 1
elif [[ $1 == -[!-]?* ]]; then
OPT=${1:0:2} OPTARG=${1:2}
elif [[ $1 == --*=* ]]; then
OPT=${1%%=*} OPTARG=${1#*=}
elif [[ ${2+.} && ${optional} == false ]]; then
OPTARG=$2 OPTSHIFT=1
elif [[ $1 == --* && ${optional} == true ]]; then
return 1
else
echo "No argument specified for '$1'."
exit 2
fi
return 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment