linuxbashshellgetopts

Handle multiple options in a bash script


I have this simple bash script

if [ $# -eq 0 ]
    then du
else
while getopts :d:h:s:r:f:a: option; do
    case $option in
        d) echo 'd';;
        h) echo 'h';;
        s) echo 's';;
        r) echo 'r';;
        f) echo 'f';;
        a) echo 'a';;
        \?) echo 'option invalide,-h pour obtenir I aide' 
    esac
done
fi

and when I call it with ./script.sh -d -a for example I would like to get "d a" returned.

Problem is I only get "d" or "a" if I call it in the other order.

How can I do to have the script doing all present options instructions ?


Solution

  • Your call to getopt declared every option to take an argument by following each name with a :. As such, script.sh -d -a recognizes the -d option with argument -a, but you ignore the argument. The same holds for script.sh -a -d: you recognize -a but ignore its -d option.

    If you omit the :s, then the options are simply flags that take no argument, and you'll see each option in turn:

    while getopts :dhsrfa option; do
    

    When you do use :, the argument provided with the option is available in the OPTARG parameter. Try your script with the following:

    while getopts :d:h:s:r:f:a: option; do
        case $option in
            d) echo "d with $OPTARG";;
            h) echo "h with $OPTARG";;
            s) echo "s with $OPTARG";;
            r) echo "r with $OPTARG";;
            f) echo "f with $OPTARG";;
            a) echo "a with $OPTARG";;
            \?) echo 'option invalide,-h pour obtenir I aide' 
        esac
    done