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 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.
$CONTAINERcommented out, so it might be better to just show the exact situation you mean. What's the code, how did you call it, what did you expect to happen, what happened instead?bash script.bash -w hello -o hello2 -t hello3 -c hello4VSbash script.bash -w hello -o hello2 -t hello3 -cVSbash script.bash -w hello -o hello2 -t hello3In other words, does getopts not mind if I just don't provite -c at all when I do some testing? I'm just trying to understand how it works