Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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

#!/bin/bash
while getopts ":j:e:" option; do
    case "$option" in
        j) MYHOSTNAME=$OPTARG ;;
        e) SCRIPT_PATH=$OPTARG ;;
        *) ;;
    esac
done

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:

j=value3
e=2
remaining=

But I would like the output as:

j=value1
e=value4
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.

share|improve this question

closed as off topic by slhck Aug 1 '12 at 12:36

Questions on Super User are expected to relate to computer software or computer hardware within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

1  
Please don't multipost, also asked on unix&linux and stackoverflow –  glenn jackman Aug 1 '12 at 11:26
    
Closing here appropriately — in the future please only post on one stack site, thanks! –  slhck Aug 1 '12 at 12:36
    
Thank you guys. I will keep that in mind. –  SiB Aug 1 '12 at 12:42

1 Answer 1

up vote 1 down vote accepted

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

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

Notice

--  

after -evalue4

And the output was

j=value1
e=value4
remaining=-Djvalue3 -pvalue2

I believe -- asks getopts to stop processing options.

share|improve this answer
2  
Manpage of getopt(3): > The special argument "--" forces an end of option-scanning regardless of the scanning mode. So, yes. This is commonly used as a safety measure in mass-assignment when filenames could be interpreted as an argument. –  slhck Aug 1 '12 at 10:16
    
Yes. I read it somewhere and then forget. Suddenly it clicked and resolved it for me. thanks anyways. –  SiB Aug 1 '12 at 10:17

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