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
Chris Davies
  • 116,213
  • 16
  • 160
  • 287
Topas
  • 23

1 Answers1

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 "
Chris Davies
  • 116,213
  • 16
  • 160
  • 287