Skip to content

Instantly share code, notes, and snippets.

@nandilugio
Created July 31, 2019 17:26
Show Gist options
  • Save nandilugio/7525c4889cb73af33c198a46824a8802 to your computer and use it in GitHub Desktop.
Save nandilugio/7525c4889cb73af33c198a46824a8802 to your computer and use it in GitHub Desktop.
Bash's getopts optional arguments hack

Details in my SO answer: https://stackoverflow.com/questions/11517139/optional-option-argument-with-getopts/57295993#57295993

getopts_get_optional_argument() {
  eval next_token=\${$OPTIND}
  if [[ -n $next_token && $next_token != -* ]]; then
    OPTIND=$((OPTIND + 1))
    OPTARG=$next_token
  else
    OPTARG=""
  fi
}

Example usage:

while getopts "hdR" option; do
  case $option in
  d)
    getopts_get_optional_argument $@
    dir=${OPTARG}
    ;;
  R)
    getopts_get_optional_argument $@
    level=${OPTARG:-1}
    ;;
  h)
    show_usage && exit 0
    ;;
  \?)
    show_usage && exit 1
    ;;
  esac
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment