I have the following code in test.sh:
while getopts "f:i:" opt; do
case $opt in
f)
echo $OPTARG
i) echo $OPTARG
Now if I run ./test.sh -f I will get the error:
option requires an argument -- i
However, when I run ./test.sh -f -i test it will echo -i.
I know that this is because it just gets the next argument separated by a space, but is there an easy way to handle this?
I could do if [ $OPTARG == "-i" ]; then exit 1 but I’m hoping there is an easier way for when I have multiple options.
If you are using getopts, it has it’s own ways. Just go with it.
After all, who says the option’s argument cannot begin with a dash? If it’s a filename, maybe the user wants the filename to begin with a dash. If it’s a number, maybe it is a negative number.