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
.
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.
EDIT: Here is the link which explains how this work.