Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading