0

我正在尝试getopts在脚本cygwin中使用。bash以下是代码:

#!/bin/bash

# Sample program to deal with getopts.

echo "Number of input arguments = $#";
i=0;

while [ ${i} -lt 10 ];
do
  i=$[${i}+1];
  echo ${i};
done

while getopts ":a:b:c:e:" opt;
do
  case ${opt} in
  a)
   echo "-a was triggered with argument: ${OPTARG}";
  ;;

  b)
  echo "-b was triggered with argument: ${OPTARG}"
  ;;

  c)
   echo "-c was triggered with argument: $[OPTARG}"
  ;;

  e)
   echo "-e was triggered with argument: ${OPTARG}"
  ;;

  ?)
   echo "Invalid argument: ${OPTARG}"
  ;;
  esac
done

当我运行上面的代码时,我收到以下错误:

./getOpts_sample.bash: line 37: syntax error near unexpected token `done'
./getOpts_sample.bash: line 37: `done'  

我无法理解此错误背后的原因。为什么getopts循环不起作用而第一个循环不起作用?是不是因为我的系统没有getopts安装?我该如何检查?

4

1 回答 1

2

这不是 cygwin 特有的;第 26 行有语法错误:

echo "-c was triggered with argument: $[OPTARG}"

替换[{,它将起作用。

第 11 行的注释:echo ${i}错误,用于echo ${!i}打印第 i 个参数。

第 10 行的注意事项:语法$[ ]现已过时;您可以(( ))像这样使用:

((i++))

甚至更好,将第 8-12 行替换为:

for ((i=0; i<10; i++)); do echo ${!i}; done
于 2013-03-16T17:49:28.283 回答