0

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.

steveb
  • 5,382
  • 2
  • 27
  • 36
MicWit
  • 655
  • 12
  • 31
  • 2
    Why are you specifying the `:` flag for `h`? That specifies that it takes an optarg, which it clearly doesn't need. – Charles Duffy Jun 03 '18 at 02:56
  • 1
    And why are you telling getopts to silence errors (by specifying a leading `:`)? If you hadn't put it in that mode, you'd *know* what the problem was, because, well, there'd be an error reported. – Charles Duffy Jun 03 '18 at 02:57
  • 1
    Also, given your use of `:`, the `-n` option *wouldn't* take an argument. You probably want `hd:n:` or `:hd:n:` (depending on whether you want to silence errors using the initial `:`). – chepner Jun 03 '18 at 02:59
  • Thanks for that, it was my lack of understanding of how getopts works to pull values out, that makes sense now. – MicWit Jun 03 '18 at 03:16

1 Answers1

1

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.

MicWit
  • 655
  • 12
  • 31