Question

I'm running bash version 4.2, and I'm trying to parse command line parameters with builtin command getopts,

But getopts doesn't seem to parse it correctly, if -s wasn't the first parameter, it won't be parsed

-s not parsed:

%> ./getopt.sh aaa -s aaa
aaa

This one get's parsed

%> ./getopt.sh -s aaa
s: aaa
aaa

The script is here:

#!/bin/bash

while getopts "bs:" opt
do
    case $opt in
        s)
            echo "s: $OPTARG"
            ;;
        *)
            echo not supported
            ;;
    esac
    shift
done

echo $1
Was it helpful?

Solution

Unlike the (older) getopt, getopts does not rearrange the arguments to put the options first. Therefore, in

./getopt.sh arg1 -s opt1

option-parsing stops as soon as the non-option arg1 is seen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top