How can I use long options with the Bash getopts builtin? How can I use long options with the Bash getopts builtin? bash bash

How can I use long options with the Bash getopts builtin?


As other people explained, getopts doesn't parse long options. You can use getopt, but it's not portable (and it is broken on some platform...)

As a workaround, you can implement a shell loop. Here an example that transforms long options to short ones before using the standard getopts command (it's simpler in my opinion):

# Transform long options to short onesfor arg in "$@"; do  shift  case "$arg" in    "--help") set -- "$@" "-h" ;;    "--rest") set -- "$@" "-r" ;;    "--ws")   set -- "$@" "-w" ;;    *)        set -- "$@" "$arg"  esacdone# Default behaviorrest=false; ws=false# Parse short optionsOPTIND=1while getopts "hrw" optdo  case "$opt" in    "h") print_usage; exit 0 ;;    "r") rest=true ;;    "w") ws=true ;;    "?") print_usage >&2; exit 1 ;;  esacdoneshift $(expr $OPTIND - 1) # remove options from positional parameters


getopts can only parse short options.

Most systems also have an external getopt command, but getopt is not standard, and is generally broken by design as it can't handle all arguments safely (arguments with whitespace and empty arguments), only GNU getopt can handle them safely, but only if you use it in a GNU-specific way.

The easier choice is to use neither, just iterate the script's arguments with a while-loop and do the parsing yourself.

See http://mywiki.wooledge.org/BashFAQ/035 for an example.


getopts is used by shell procedures to parse positional parameters of 1 character only(no GNU-style long options (--myoption) or XF86-style long options (-myoption))