Getops 将我的期权链视为第一个的论据

Getops consider my option chain as the argument for the first one

以下代码在subscript.sh中执行,subscript.shprimaryscript.sh

里面是运行
#### primaryscript.sh
#! /bin/bash
#...
"$bss_path"/subscript.sh "$option"
#...

我正在使用这段代码来解析我的参数及其值:

#### 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

当我用多个参数调用我的脚本时出现问题:

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

getops 认为选项 l5.0.3-0 -s 4.0-0 -b 010 作为参数。

我做错了什么? 我试着玩弄 : 和选项,但据我所知,我必须把它们放在选项后面,对吗? 而getops自然知道-是参数的分隔符

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

对我有用。您可以通过在 shell 中键入 "man bash" 并搜索来阅读有关 GETOPTS、OPTARG 以及 while 循环和 case 语句的更多信息。

#!/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

输出:

5.0.3-0
010
4.0-0

正如 Cyrus 在评论中指出的那样,问题在于我如何传递参数。

./myscript "$options"

正确的方法是:

./myscript $options

因为“$options”不关心空格并将整个字符串作为单个参数。