0

How can I use getopt or getopts with subcommands and long options, not with short options? I know how to implement short and long options with getopts. Solutions that I've found so far are using getopts in subcommand switch-case but with short options, for example:

https://stackoverflow.com/questions/402377/using-getopts-to-process-long-and-short-command-line-options

Using getopts to parse options after a non-option argument

How can I implement for example following subcommands and their long options?:

 $> ./myscript.sh help
show
show --all
set
set --restart
reset
reset --restart
help
2
  • Please edit your question and add links to the solutions you found. Do you know how to implement long options without subcommands?
    – Bodo
    Apr 7, 2022 at 10:30
  • IMHO when you have sub-commands it's easier to write the whole thing without any getopt/getopts
    – Fravadona
    Apr 7, 2022 at 10:37

1 Answer 1

1

Parse them manually in a function, and call the function with the "$@". After the call, any residual non-options are in $1, $2, etc. Note, in this example, I'm using associative arrays to hold the switches. If you don't have bash 3 or later, you can use global variables instead.

The subcommand will be args[0] and its options in the rest.

usage() { 
  echo "${0##*/} [options...] args ... "
}
version() { 
  echo "0.1"
}

parse_opt() {
  while [[ -n "$1" ]]; do
    case "$1" in
    --) break ;; 
    
    ## Your options here:
    -m) opts[m]=1 ;;
    -c|--center) opts[c]="$2" ; shift ;;
    -x) opts[x]=1 ;;

    ## Common / typical options
    -V) version; exit 0 ;;
    --version) 
        version; exit 0 ;;
    -?|--help)
        usage ; exit 0 ;;
    -*)
        echo >&2 "$0: Error in usage."
        usage
        exit 1
        ;;
    *)  break ;;
    esac
    shift
  done
  args=("$@")
}

declare args
declare -A opts # assoc array
parse_opt "$@"

case "${args[0]}" in
  sub1)  
    "${args[@]}" ;;
  *) 
    echo >&2 "Unknown sub-command"
    exit 1
esac

1
  • associative arrays are bash 4+
    – Fravadona
    Apr 7, 2022 at 13:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .