3

I am writing a bash script which accept parameters. I am using getopts to achieve it.

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

pahan
  • 2,445
  • 1
  • 28
  • 36

2 Answers2

2

At line 4 you probably want case "$opt" in (quote $opt). Otherwise if it contains a metacharacter it could fail.

Benoit
  • 76,634
  • 23
  • 210
  • 236
2

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. Overall code would be (also demonstrating a flag -h not taking arguments):

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
bobah
  • 18,364
  • 2
  • 37
  • 70
  • I believe you are correct. but :a worked I dont know why. I just cleaned the script body and it works now. – pahan Dec 29 '11 at 05:18
  • Beware! This answer introduces breaking changes to the OP's code: -- `:a` vs `a:` - when used as optspec, the first form instructs getopts to use silent error reporting and to expect option `a` to have **no** argument, while the second form means: use verbose error report and expect option `a` to have an argument; -- `\?)` vs `?)` - when silent error reporting is ON, the first form will match only invalid options encountered by getopts, while the second form will match invalid options, options with missing arguments, and valid options unimplemented in the case statement. – UrsaDK Jan 21 '19 at 07:38