Veera Veera - 6 months ago 8
Linux Question

How to prevent passing parameters to arguments that don't take one in getopt?

For example consider this script,

#!/bin/sh

OPTS=`getopt -o ahb:c: --long help,name:,email: -- "$@"`
#echo "$OPTS"
eval set -- "$OPTS"

usage () {
echo "type -h for help"
}


while true; do
case "$1" in
-a) echo "a is a short option that do not take parameters"; shift ;;
-b) echo "b is a short option that requires one parameter and you specified $2"; shift 2;;
-c) echo "c is a short option that requires one parameter and you specified $2"; shift 2;;
--name) echo "your name is $2"; shift 2;;
--email) echo "your email is $2"; shift 2;;
-h | --help) echo "Google search yourself !"; shift 1;;
--) usage ; shift; break ;;
*) echo "hello"; break ;;

esac
done


So if call the script as
sh myscript.sh -a hello
, it should throw an error telling that -a does not take any parameters.

Is there a way to do it ?

I-V I-V
Answer

The problem you have is because you don't want a "second" parameter but it's actually third parameter!

If you don't want any parameter after -a then you need to check if $3 exists or not. ($2 will be '--')

Here is the fixed code that will print an error when suppling something after -a:

#!/bin/sh

OPTS=`getopt -o ahb:c: --long help,name:,email: -- "$@"`
#echo "$OPTS"
eval set -- "$OPTS"

usage () {
    echo "type -h for help"
}


while true; do
    case "$1" in
        -a) if [ ! -z "$3" ] ; then 
#Check if there is something after -a
                echo "a is a short option that do not take parameters";
else
         echo "Whatever..";
fi
 shift ;;
        -b) echo "b is a short option that requires one parameter and you specified $2"; shift 2;;
        -c) echo "c is a short option that requires one parameter and you specified $2"; shift 2;;
        --name) echo "your name is $2"; shift 2;;
        --email) echo "your email is $2"; shift 2;;
        -h | --help) echo "Google search yourself !"; shift 2;;
        --) usage ; shift; break ;;
        *) echo "hello"; break ;;

    esac
done

I hope this is what you were looking for :)

Comments