15

I'm new to shell scripting, learning it independently, and I'm seeing a lot of scripts with a usage() function. For example:

 usage()  
 {  
 echo "Usage: $0 filename"  
 exit 1  
 } 

Which kind of functions should be called usage? And is there relation to "usage statement"? I couldn't find any basic definition for this...

1
  • For more detailed descriptions in a usage() you can use a heredoc see: Here Documents - The Linux Documentation Project. Which is often what you find when the usage() gives detailed information on the script, along with a list of options and a description of each. It prevents using numerous echo or printf statements one after the other... Jan 3, 2016 at 4:20

2 Answers 2

23

It's a just a convention. When something is wrong with the values supplied on the command line, people often use a function called usage() to tell you the problem/the values expected. For example:

#!/bin/sh
if [ $# -ne 1 ] ; then
    usage
else
    filename=$1
fi
...
3
  • 2
    Also convention: print usage to stdout (&1) when help (-h,--help) is requested; print usage to stderr (&2) otherwise.
    – rubicks
    Jan 2, 2016 at 17:04
  • 1
    The "();" in the given example does not appear to be in POSIX. Jan 2, 2016 at 20:17
  • Right you are, a little c crept in there. Removed. Jan 3, 2016 at 4:09
6

When you check the arguments sent to the program, you'll sometimes have to notify the user that they failed the command.

For example, if you expect your program to be called with myprogram filename, then you will call usage if there is no parameter or more than 1 parameter.

Instead of having the same message at several locations in your code with the content of usage, it's a better practice to do only one function.

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.