How to pass in shell scripts mandatory and optional flags in command line using getopts?
<p>I want to pass 3 parameters with getopts to my shell script. The script requires at least the first 2, the third parameter is optional. If it is not set, its default is used. So that the following would both work:</p>

<pre><code>sh script.sh -a "/home/dir" -b 3
sh script.sh -a "/home/dir" -b 3 -c "String"
</code></pre>

<p>I tried to do it like the following, but it constantly ignores my entered parameters.</p>

<pre><code>usage() {
 echo "Usage: Script -a &lt;homedir&gt; -b &lt;threads&gt; -c &lt;string&gt;"
  echo "options:"
                echo "-h      show brief help"

  1&gt;&amp;2; exit 1;
}

string="bla"

while getopts h?d:t:a: args; do
case $args in
    -h|\?)
        usage;
        exit;;
    -a ) homedir=d;;
    -b ) threads=${OPTARG};;
    -c ) string=${OPTARG}
        ((string=="bla" || string=="blubb")) || usage;;
    : )
        echo "Missing option argument for -$OPTARG" &gt;&amp;2; exit 1;;
    *  )
        echo "Unimplemented option: -$OPTARG" &gt;&amp;2; exit 1;;
  esac
done
</code></pre>

<p>I'm new to this getopts, before I just added the parameters in a specific order, which I don't want to do here. I have read a lot questions in here, but unfortenatly didn't find it the way I need it.</p>

<p>I really would appriciate your help here. Thanks:)</p>