I'm on OSX, and I need a bash script that handles multiple arguments. Based on some answers on this website, I wrote the following bash script (some strings have been removed for privacy):
#!/bin/bash
# A POSIX variable
OPTIND=1 # Reset in case getopts has been used previously in the shell.
# Default parameter value:
PORT=xxx
PUBKEY=xxx
HOST_IP=xxx
# show_help function
show_help() {
echo "Usage: $(basename "$0") [-h] [-p PORT] [-f PUBKEY] [-i HOST_IP]"
echo
echo " -p PORT add key to container running on port PORT (default: xxx)"
echo " -f PUBKEY add key file PUBKEY (default: xxx)"
echo " -i HOST_IP connect to host HOST_IP (default: xxx)"
echo
return
}
while getopts ":h:p:f:i:" option; do
case "$option" in
\?)
echo "invalid argument"
show_help
exit 1
;;
h)
show_help
exit 0
;;
p) PORT=$OPTARG
;;
f) PUBKEY=$OPTARG
;;
i) HOST_IP=$OPTARG
;;
esac
done
shift $((OPTIND-1))
USER_AT_HOST="root@$HOST_IP"
PUBKEYPATH="$HOME/.ssh/$PUBKEY"
ssh-copy-id -i "$PUBKEYPATH" "$USER_AT_HOST" -p "$PORT"
exit 0
the script works with all arguments (including an invalid argument), except for the argument -h
. When I call the script as
script.sh -h
the result is the same as
script.sh
instead of showing me the help. Can you help me understand what's happening?
CodePudding user response:
The :
after h
in getopts ":h:p:f:i:"
means that -h
requires an argument, but I don't think -h
needs any arguments. Remove the colon after h
.
Normally, getopts would display an error:
option requires an argument -- h
But, as you started the string with another colon, error reporting was turned off. Remove the initial :
to see the errors in argument processing.
CodePudding user response:
In the getopts
pattern h:
says that -h
must have an argument (eg, -h 2
) so, have you tried script.sh -h 2
?
If -h
should not have any args then remove the :
after the h
leaving you with getopts ":hp:f:i:"