1

I want to escape the first string SOMETEXT in the getopts args. But I'm only able to do it in the first example.

How can I make it work on the second example?

while getopts p: opt
do
   case $opt in
   p) result=$OPTARG;;
   esac
done

echo "The result is  $result "

Example 1:

run_test.ksh -p3 SOMETEXT
The result is  3

Example 2:

run_test.ksh SOMETEXT -p3
./run_test.ksh: line 10: result: parameter not set
1

This is a consequence of using getopts. Parameters and their arguments must come before any other text.

If you know that the first word is SOMETEXT you could strip it from the argument list that getopts processes:

if [[ 'SOMETEXT' == "$1" ]]
then
    echo "Found SOMETEXT at the beginning of the line"
    shift
fi

while getopts p: opt
do
   case $opt in
   p) result=$OPTARG;;
   esac
done

echo "The result is  $result "
  • Hello Roiama ! Thank you for your comment. With shift I'm able to do it. – Topas Dec 9 '16 at 14:03

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.