Pergunta

I am trying to use getopts on cygwin in a bash script. The following is the code:

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

When I run the above code, I get the following error:

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

I am not able to understand the cause behind this error. Why does the getopts loop not work while the first one does? Is it because my system does not have getopts installed? How do I check for that?

Foi útil?

Solução

This is not specific to cygwin; there is a syntax error line 26:

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

replace [ with { and it will work.

Note for line 11: echo ${i} is wrong, use echo ${!i} to print the i-th arg.

Note for line 10: the syntax $[ ] is now obsolete; you may use (( )) instead like this :

((i++))

or even better, replace lines 8-12 by:

for ((i=0; i<10; i++)); do echo ${!i}; done
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top