LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   getopt command handling (https://www.linuxquestions.org/questions/linux-newbie-8/getopt-command-handling-4175465413/)

Rasna 06-10-2013 08:14 AM

getopt command handling
 
Hi,
while using getopt for reading the commandline args for my script I am expecting it to be reading allowed values or else exit with error.
pls find the code getopt.sh
Code:

#!/bin/bash

# getopt.sh example

echo "BEFORE GETOPT: $@";

# Execute getopt
ARGS=$(getopt -o a:b:c -l "ay:,bee:cee" -n "getopt.sh" -- "$@");

#Bad arguments
if [ $? -ne 0 ];
then
echo "ERROR ...."
 exit 1
fi
echo "BEFORE GETOPT: $@";

eval set -- "$ARGS";

So here I am expecting my script will accept args
-a, -b, -c , --ay ,--bee , --cee only and if not it should fail with ERROR.
But it is not failing in that case. How to make my script fail incase of wrong value of args?
OUTPUT:
1: SUCCESS case
# ./getopt.sh -a value
BEFORE GETOPT: -a value
BEFORE GETOPT: -a value
2:FAILURE CASE(SHOULD FAIL!!!)
# ./getopt.sh -am value
BEFORE GETOPT: -am value
BEFORE GETOPT: -am value
3:FAILURE CASE(SHOULD FAIL!!!)
# ./getopt.sh -be value
BEFORE GETOPT: -be value
BEFORE GETOPT: -be value

Thanks in advance
Rasna

rknichols 06-10-2013 10:37 AM

When you invoke as "./getopt.sh -am value", the "m" will be taken as the argument for the "-a" option and "value" is then a non-option positional parameter. The situation is similar for "./getopt.sh -be value".

Rasna 06-11-2013 04:48 AM

The scenarios like
# ./getopt.sh --be value

# ./getopt.sh --ce value

# ./getopt.sh --be value
BEFORE GETOPT: --be value
BEFORE GETOPT: --be value

ideally it should be --cee and --bee.. But still it is accepting succesfully --ce and --be
How to resolve this?

rknichols 06-11-2013 08:04 AM

Quote:

Originally Posted by Rasna (Post 4969419)
ideally it should be --cee and --bee.. But still it is accepting succesfully --ce and --be
How to resolve this?

The manpage for getopt specifically states:
"Long options may be abbreviated, as long as the abbreviation is not ambiguous."
One way to block that behavior would be to declare another option that differs only in the final letter, e.g. "ceX" and "beX", and then handle those option as errors.

Rasna 06-11-2013 08:13 AM

Thank you very much !


All times are GMT -5. The time now is 02:18 AM.