2

I have a file parsing option flags from command line input, and if you pass in -h, it's giving an error.

h)  
    usage
    exit 1
;;

returns: usage: command not found

Does anybody know what’s going on here? I've found many examples that use usage, so I would think it should work. I can’t seem to find any relevant info on it searching google.

Francis Lewis
  • 8,872
  • 9
  • 55
  • 65

4 Answers4

5

You need add to your shell script before you call the usage the next:

usage() {
    echo  "$0: some help text"
}
clt60
  • 62,119
  • 17
  • 107
  • 194
3

What you are missing is a function definition of usage:

function usage {
    cat <<-USAGE
         Now you can define your usage here
         take as many lines as you want. When
         you finish, just put "USAGE" on a line
         by itself.
    USAGE
}

Put this BEFORE the call of usage. Remember that the line with USAGE must be preceded only by tabs.

David W.
  • 105,218
  • 39
  • 216
  • 337
  • In case it's not clear to the readers of this answer, the `<<-` heredoc will strip of leading **tab** characters, not any arbitrary whitespace. ref: http://www.gnu.org/software/bash/manual/bashref.html#Here-Documents – glenn jackman Apr 03 '14 at 20:26
  • 1
    I mentioned that it _must be preceded only by tabs_, but you're right it's still not clear. I like doing it this way because it's easier to provide multiple line usage instructions. – David W. Apr 03 '14 at 20:31
2

Those working examples define a function called usage in their source.

As you see, it gets called, when you provide the -h flag.

The usual reason behind moving it to a function is that

  • it doesn't clutter the code
  • can be reused, e.g. when you provide invalid arguments.
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
1

usage is not a command, but the common name for a custom shell function you supply that outputs usage information for your script.

chepner
  • 497,756
  • 71
  • 530
  • 681