user3299633 user3299633 - 5 months ago 11
Linux Question

getopts is not sending my options to standard out

I'm beginning to experiment with getopts but am running into a few errors. When I enter an invalid option such as -A the program output is not what it needs to be.

#!/bin/bash

function usage() {
echo "Usage: $0 -h [database host] -d [test database name]"
exit 1
}

while getopts “:h:d:” opt; do
case ${opt} in
h)
db_host=$OPTARG
;;
d)
test_db=$OPTARG
;;
\?)
echo "Invalid option: -$OPTARG" 1>&2
usage
exit 1
;;
:)
echo “Option -$OPTARG requires an argument.” 1>$2
usage
exit 1
;;
esac
done
shift $((OPTIND-1))

if [ -z $db_host ] || [ -z $test_db ]; then
usage
else
echo "Your host is $db_host and your test database is $test_db."
fi


Example program output:

./opt.sh: illegal option -- A
Invalid option: -
Usage: ./opt.sh -h [database host] -d [test database name]


So, basically two questions:

1) I want to get rid of this first error message altogether. I want to provide my own error messages.
2) Why isn't my script producing "Invalid option: -A" instead of just "Invalid option: -"

Answer

You have the wrong types of quotes around the options argument to getopts, they're "curly quotes" instead of ASCII double quotes. As a result, : wasn't the first character of the options, so you weren't getting silent error reporting.

Change it to

while getopts ':h:d:' opt; do
Comments