Bash – How to detect that no options were passed with getopts

bashgetoptsoptionsshell

I have this code –

#getoptDemo.sh
usage()
{
    echo "usage: <command> options:<w|l|h>"
}
while getopts wlh: option
do
    case $option in
            (w)
                    name='1';;
            (l)
                    name='2';;
            (h)
                    name='3';;
            (*)
                    usage
                    exit;;
    esac
done
print 'hi'$name

When I run bash getoptDemos.sh (without the option) it prints hi instead of calling the function usage. It calls usage when options other than w, h and l are given. Then can't it work when no options are specified.

I have tried using ?, \?, : in place of * but I can't achieve what I wanted to. I mean all the docs on getopt says it to use ?.

What am I doing wrong?

Best Answer

When you run this script without any options, getopt will return false, so it won't enter the loop at all. It will just drop down to the print - is this ksh/zsh?

If you must have an option, you're best bet is to test $name after the loop.

if [ -z "$name" ]
then
   usage
   exit
fi

But make sure $name was empty before calling getopts (as there could have been a $name in the environment the shell received on startup) with

unset name

(before the getopts loop)

Related Question