Skip to content

Instantly share code, notes, and snippets.

@midenok
Created January 27, 2023 10:53
Show Gist options
  • Save midenok/7e0f3d218869fbad9e17c1dea98ab9c5 to your computer and use it in GitHub Desktop.
Save midenok/7e0f3d218869fbad9e17c1dea98ab9c5 to your computer and use it in GitHub Desktop.
Bash getopts optional arg
optional_arg() {
eval local next_token=\$$((OPTIND + 1))
if [[ -n $next_token && $next_token != -* ]]; then
OPTIND=$((OPTIND + 1))
OPTARG=$next_token
[[ -n "$1" ]] &&
eval $1=\$next_token
else
OPTARG=""
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment