Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getopts not working - bash

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

like image 486
pahan Avatar asked Mar 03 '26 02:03

pahan


2 Answers

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

like image 94
Benoit Avatar answered Mar 05 '26 19:03

Benoit


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
like image 45
bobah Avatar answered Mar 05 '26 18:03

bobah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!