Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is usage() in shell scripting?

Tags:

linux

shell

unix

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...

like image 933
user1508682 Avatar asked Jan 02 '16 16:01

user1508682


People also ask

What does usage () mean in C?

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.

What is usage command in Linux?

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.

How do I see Bash script usage?

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 .

What does $() mean bash?

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).


2 Answers

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
...
like image 143
John Hascall Avatar answered Sep 28 '22 08:09

John Hascall


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.

like image 29
Pierre Emmanuel Lallemant Avatar answered Sep 28 '22 08:09

Pierre Emmanuel Lallemant