I have a shell script testShell.sh which uses getopts as below:

while getopts ":j:e:" option; do
    case "$option" in
        j) MYHOSTNAME=$OPTARG ;;
        e) SCRIPT_PATH=$OPTARG ;;
        *) ;;

echo "j=$MYHOSTNAME"
echo "e=$SCRIPT_PATH"
shift $((OPTIND - 1))
echo "remaining=$@"

When I test run it like following:

$ testShell.sh  -jvalue1 -evalue4 -Djvalue3  -pvalue2

The output which I get is following:


But I would like the output as:

remaining=-Djvalue3 -pvalue2

Is it possible to make sure that getopts only looks at first character post - symbol? so that it doesn't interpret -Djvalue3 as -jvalue3 and -pvalue2 as -e2.


try this:

$ ./testShell.sh  -j value1 -e value4 -D jvalue3  -p value2
remaining=jvalue3 -p value2

Note the spaces between the options and the option strings.

help getopts says:

OPTSTRING contains the option letters to be recognized; if a letter
is followed by a colon, the option is expected to have an argument,
which should be separated from it by white space.

i.e. the space between option and any option string is required.

If you need more than the bash built-in getopt is capable of, the /usr/bin/getopt utility supports both long and short options, with or without spaces between options and option string. also supports extra features like optional string args.

BTW, /usr/bin/getopt is available in the util-linux package in debian and derivatives like ubuntu...dunno about other distros or *nixes, but the source will be available from the debian archives if you can't find it anywhere else.

  • +1. Your space gave me the directions to get to the -- option. thanks. – Bharat Sinha Aug 1 '12 at 10:18

After posting it on 3 forums and searching everywhere... eventually I tried the following and it worked...

testShell.sh  -jvalue1 -evalue4 -- -Djvalue3  -pvalue2



after -evalue4

And the output was

remaining=-Djvalue3 -pvalue2

I believe -- asks getopts to stop processing options.

  • I'm glad it kind of works for you...but...while this may work in your current situation it is unlikely to work in all and you'll likely have occasional strange behaviour because you insist on using getopts contrary to the documentation which says that the space between the opt and the optstring is required. using -- here is a hack, not a fix. – cas Aug 1 '12 at 10:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.