user1585121
user1585121

Reputation:

Getopts considers my option chain as the argument for the first one

The following code is executed in subscript.sh, and subscript.sh is run inside primaryscript.sh

#### primaryscript.sh
#! /bin/bash
#...
"$bss_path"/subscript.sh "$option"
#...

I am using this code to parse my arguments and their values:

#### subscript.sh
#! /bin/bash

while getopts "hw:l:s:b:" opt; do
  case $opt in
    w)
      x="$OPTARG";;
    l)
      xx="$OPTARG";;
    s)
      xxx="$OPTARG";;
    b)
      xxxx="$OPTARG";;
    h)
      print_usage
      exit 0;;  
    \?)
      echo "Invalid option: -$OPTARG"
      exit 1;;
  esac
done

The problem appears when I call my script with multiple arguments:

./myscript -l 5.0.3-0 -s 4.0-0 -b 010

getopts thinks that option l have 5.0.3-0 -s 4.0-0 -b 010 as argument.

What am I doing wrong?

I tried to play around with the : and the option, but as I understood I have to put them behind the options taking an argument right?

And getopts naturally knows that - is the separator for arguments.

$> echo $BASH_VERSION
$> 3.2.25(1)-release

Upvotes: 1

Views: 238

Answers (2)

Jacek Trociński
Jacek Trociński

Reputation: 920

It works for me. You can read more about GETOPTS, OPTARG as well as the while loop and case statement by typing "man bash" in your shell and searching.

#!/bin/bash

while getopts "hw:l:s:b:" opt; do
  case $opt in
    w)
      x="$OPTARG";;
    l)
      xx="$OPTARG";;
    s)
      xxx="$OPTARG";;
    b)
      xxxx="$OPTARG";;
    h)
      print_usage
      exit 0;;
    \?)
      echo "Invalid option: -$OPTARG"
      exit 1;;
  esac
done

echo $xx
echo $xxxx
echo $xxx

Output:

5.0.3-0
010
4.0-0

Upvotes: 0

user1585121
user1585121

Reputation:

As Cyrus pointed out in the comment, the problem was how I passed arguments.

./myscript "$options"

The correct way is :

./myscript $options

Since "$options" won't care of the spaces and take the whole string as a single argument.

Upvotes: 1

Related Questions