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
At line 4 you probably want case "$opt" in
(quote $opt
). Otherwise if it contains a metacharacter it could fail.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.