getopts does not work – bash… here is a solution to the problem.
getopts does not work – bash
I’m writing a bash script that accepts parameters. I’m using getopts to implement 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 the above code returned this error to me.
'etOpts_test.sh: line 4: syntax error near unexpected token `in
'etOpts_test.sh: line 4: ` case $opt in
I’m using CentOs 5.5
Solution
In line 4, you may need case "$opt" in
(reference $opt
). Otherwise, if it contains a metacharacter, it may fail.