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...
A usage statement is a printed summary of how to invoke a program from a shell prompt (i.e. how to write a command line). It will include a description of all the possible command-line arguments that the program might take: how many command-line arguments there are. what each command-line argument represents.
The du command is a standard Linux/Unix command that allows a user to gain disk usage information quickly. It is best applied to specific directories and allows many variations for customizing the output to meet your needs. As with most commands, the user can take advantage of many options or flags.
There are multiple ways to show script usage inside of your Bash script. One way is to check if the user has supplied the -h or --help options as arguments as seen below. #!/bin/bash # check whether user had supplied -h or --help .
Example of command substitution using $() in Linux: Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).
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
...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With