1

I want to have getopts setup for my script in such a way that it accepts no argument (-p) but so that it can also accept an argument (-p library). Both need to be accepted. They're (argument and no argument) are both allowed. The argument should be allowed to be any string. See below:

while getopts "p:sdih" opt; do
                case ${opt} in
                        p )
                                #WHEN NO ARGUMENT IS GIVEN, DO THIS

                                selection="plex"

                                #WHEN AN ARGUMENT IS GIVEN, DO THIS

                                selection="plex"
                                argument=true
                                optarg="$OPTARG"
                                ;;

                        s )
                                selection="sonarr"
                                ;;

                        d )
                                selection="deluge"
                                ;;
                        i )
                                selection="info"
                                ;;

                        h )
                                usage | column -t -s "|"
                                exit
                                ;;
                        \? )
                                echo "Invalid option"
                                usage | column -t -s "|"
                                exit
                                ;;
                esac
        done 2>/dev/null
        shift $((OPTIND -1))

That's how it needs to work. But I'm new to getopts so I don't know how to do this yet...

1 Answer 1

0

To check for missing arguments, start optstring with a colon : by changing "p:sdih" to ":p:sdih"

Then, add a case argument before \?) like so:

:) echo "Option $OPTARG has no argument."
   exit
   ;;

You can check for more than one option by evaluating "$OPTARG"

If an option-argument is missing:

  • If the first character of optstring is a colon, the shell variable specified by name shall be set to the character and the shell variable OPTARG shall be set to the option character found.

  • Otherwise, the shell variable specified by name shall be set to the question-mark character, the shell variable OPTARG shall be unset, and a diagnostic message shall be written to standard error. This condition shall be considered to be an error detected in the way arguments were presented to the invoking application, but shall not be an error in getopts processing; a diagnostic message shall be written as stated, but the exit status shall be zero.

More information can be found here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.