Search code examples
shellgetopts

What does the -: following the last opt char do?


I saw a getopts usage like this:

while getopts ":hv-:" optchar; do
...
done

What is the use of the last -:, with this placement, what the - and : have to do with the parsing behavior?


Solution

  • The :-: at the end of the optstring (":hv-:") is used to handle long options (options starting with --). The placement of - and : after the v does not directly impact the behavior of the v option.

    Here's the breakdown:

    : at the beginning of the optstring suppresses error messages for invalid options.
    h and v are valid short options.
    The hyphen (-) after v indicates that v can take an optional argument.
    The double hyphen (--) is used to indicate the end of options and to handle long options.
    The last colon (:) at the end is a part of the getopts syntax and is associated with handling the long options.
    

    The getopts command uses the -- to distinguish between short and long options. When a long option is encountered, it is handled in the --) case inside the getopts loop. The colon (:) after the - in :-: is associated with long options that require arguments. For example, if you have a long option like --input=file.txt, the : after - allows you to specify that input requires an argument.

    Here's a brief example:

    while getopts ":hv-:" optchar; do
      case "${optchar}" in
        h)
          echo "Short option h detected."
          ;;
        v)
          echo "Short option v detected."
          ;;
        -)
          case "${OPTARG}" in
            h)
              echo "Long option --h detected."
              ;;
            v)
              echo "Long option --v detected."
              ;;
            *)
              echo "Invalid long option: --${OPTARG}"
              ;;
          esac
          ;;
        \?)
          echo "Invalid option: ${OPTARG}"
          ;;
      esac
    done
    
    

    In this example, short options -h and -v are handled, and long options --h and --v are also handled. The :-: in the optstring enables the handling of long options and their potential arguments.