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?
echo invalid argument >&2; exit 1. Do not show a usage statement in response to an error. Print the error message to stderr and exit non-zeroecho "illegal option -$OPTARG (-h for usage)" >&2. It may seem helpful to print a usage statement, but it really isn't. Go to a directory that is not managed by git and typegit diff. You will probably (depending on the version) see an irrelevant message telling you about such useful options as--ext-diffand--color-moved-wsand--skip-to, but the useful information that you are not in a git repo has scrolled off the top of the terminal. Keep the error message succinct, relevant, and accurate. Don't give wall of text.show_helpafterecho "invalid argument". Will do