So I want to be able to use a -h option to show the help details. I have:
while getopts ":h:d:n" opt; do
case $opt in
h) help="true" >&2
;;
d) vdir="$OPTARG"
;;
n) vname="$OPTARG"
;;
\?) echo "Error: Invalid option -$OPTARG" >&2
echo "Please use -h for more information"
exit 1
;;
esac
done
# If -h was used, display help and exit
if [ "$help" = "true" ]; then
echo "Help details"
fi
When I pass in details for -d or -n (eg. program -d /var/test/) it receives them fine. However when I do something like program -h, it doesn't work.
I have also tried echoing a line when I do the h) option in the case statement, however, it doesn't get echoed. It seems that when I do -h it doesn't work, I have to send in a value as well (eg program -h "test") and it will do whats required.
If I do something like program -p it shows the error message as is required, -h just does nothing though.
As per comments, the -h does not have a value so should not have a : after it, so that line should be:
while getopts "hd:n:" opt; do
Removing the initial : will give errors. Having no : after the h will mean it does not need a value, while the : after d and n means they need a value.