Question

Have some script with getopts. It includes next:

while getopts "hlcpx:" opt; do
  case $opt in
    h)
      usage && exit 1
      ;;
    l)
      last=1
      current=""
      ;;
    c)
      current=1
      last=""
      ;;
    p)
      prints=1
      exports=""
      ;;
    x)
      exports=1
      prints=""
      ;;
    \?)
      usage && exit 1
      ;;
  esac
done

echo "Using: current=$current last=$last prints=$prints exports=$exports"

But - when I run it with options -x and -c I got:

$ ./version.sh -x -l
Using: current= last= prints= exports=1

$ ./version.sh -x -c
Using: current= last= prints= exports=1

If I remove : - it works correctly:

$ cat version.sh | grep whil
while getopts "hlcpx" opt; do

$ ./version.sh -x -c
Using: current=1 last= prints= exports=1

$ ./version.sh -x -l
Using: current= last=1 prints= exports=1

What I'm doing wrong? Thanks.

Was it helpful?

Solution

getopts works as designed. If you don't need to pass a parameter to the -x option, don't append : to x in the getopts option string.

Alternatively, use your script with the expected syntax, eg:

./version.sh -x foo -c
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top