简体   繁体   English

getopts无法正常工作-bash

[英]getopts not working - bash

I am writing a bash script which accept parameters. 我正在编写一个接受参数的bash脚本。 I am using getopts to achieve it. 我正在使用getopts来实现它。

#!/bin/bash

while getopts ":a" opt; do
  case $opt in
    a)
      echo "-a was triggered!" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      ;;
  esac
done

but above code return's me this error. 但是上面的代码返回是我这个错误。

'etOpts_test.sh: line 4: syntax error near unexpected token `in
'etOpts_test.sh: line 4: `  case $opt in

I am using CentOs 5.5 我正在使用CentOs 5.5

At line 4 you probably want case "$opt" in (quote $opt ). 在第4行,您可能希望在case "$opt" in (quote $opt )。 Otherwise if it contains a metacharacter it could fail. 否则,如果它包含一个元字符,则可能会失败。

It should be a: , not :a to denote a flag requiring an argument, also question mark should not be quoted as it serves as wildcard symbol. 它应该是 ,而不是:a来表示需要参数的标志,也不应加问号,因为它用作通配符。 Overall code would be (also demonstrating a flag -h not taking arguments): 总体代码将是(还显示一个标志-h不带参数):

function usage {
  echo "usage: ..."
}

a_arg=
while getopts a:h opt; do
  case $opt in
    a)
      a_arg=$OPTARG
      ;;
    h)
      usage && exit 0
      ;;
    ?)
      usage && exit 2
      ;;
  esac
done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM