Skip to main content
3 of 4
Clarify in title
Kusalananda
  • 355.9k
  • 42
  • 735
  • 1.1k

Handling unused getopts argument (are options not mandatory?)

I have a script that starts with getopts and looks as follows:

USAGE() { echo -e "Usage: bash $0 [-w <in-dir>] [-o <out-dir>] [-c <template1>] [-t <template2>] \n" 1>&2; exit 1; }

if (($# == 0))
then
    USAGE
fi

while getopts ":w:o:c:t:h" opt
do
    case $opt in
        w ) BIGWIGS=$OPTARG
        ;;
        o ) OUTDIR=$OPTARG
        ;;
        c ) CONTAINER=$OPTARG
        ;;
        t ) TRACK=$OPTARG
        ;;
        h ) USAGE
        ;;
        \? ) echo "Invalid option: -$OPTARG exiting" >&2
       exit
        ;;
        : ) echo "Option -$OPTARG requires an argument" >&2
        exit
        ;;
    esac
done

more commands etc

echo $OUTDIR
echo $CONTAINER

I am fairly new to getopts. I was doing some testing on this script and at some stage, I didn't need/want to use the -c argument [-c ]. In other words, I was trying to test another specific part of the script not involving the $CONTAINER variable at all. Therefore, I simply added # in front of all commands with the $CONTAINER and did some testing which was fine.

When testing the script without using $CONTAINER, I typed:

bash script.bash -w mydir -o myoutdir -t mywantedtemplate

However, I was wondering, given my getopts command I didn't get a warning. In other words, why did I not get a warning asking for -c argument. Is this possible? Does the warning only occur if I type:

bash script.bash -w mydir -o myoutdir -t mywantedtemplate -c

UPDATE

After doing some testing, I think that is it:

  • If you don't explicitly write "-c", getopts won't "ask" you for it and give you an error (unless your script is doing something with it - i.e. if you haven't put # in front of each command using this argument)
  • You only get an error if you put "-c " and nothing else

Is this correct? Presumably what I did was "bad practise" and should be avoided: when testing, I should just remove the c: from the getopts command entirely.

I guess what I am asking is: when you tell getopts about the arguments (the "while" line in my script), are we saying: these are the options you can expect and the ones followed by a ":" should have argument with them. BUT they don't HAVE to be given. I.e. you can expect an c option with an argument but don't throw an error if you are not given the c option at all.

mf94
  • 229
  • 2
  • 3
  • 7