Create usage messages

From Linux Bash Shell Scripting Tutorial Wiki
Jump to navigation Jump to search

← Parameters Set by the ShellHomeExit command →

You can use the if command to check command line arguments. Many Linux commands display an error or usage information when required command line option is not passed. For example, try the following command:


Sample outputs:

gcc: no input files

Try rm command:


Sample outputs:

rm: missing operand
Try `rm --help' for more information.

How Do I Add Usage Functionality To The Script?

A shell script that depends upon user input must:

  • Verify the number of arguments passed to it.
  • Display an error or usage message if arguments or input is not passed to the script. Your shell script can also create such usage message using if command and $# special shell variable parameter. Create a shell script called
# A shell script to lookup usernames in /etc/passwd file
# Written by: Vivek Gite 
# Last updated on: Sep/10/2003
# -------------------------------------------------------
# Set vars
user=$1   # first command line argument

# Verify the type of input and number of values
# Display an error message if the username (input) is not correct
# Exit the shell script with a status of 1 using exit 1 command.
[ $# -eq 0 ] && { echo "Usage: $0 username"; exit 1; }
grep "^$user" $passwddb >/dev/null
retval=$?    # store exit status of grep

# If grep found username, it sets exit status to zero
# Use exit status to make the decision 
[ $retval -eq 0 ] && echo "$user found" || echo "$user not found"

Save and close the file. Run it as follows:

chmod +x

Sample outputs:

Usage: ./ username

Pass the command line argument kate:

./ kate

Sample outputs:

kate not found

Pass the command line argument vivek:

./ vivek

Sample outputs:

vivek found

← Parameters Set by the ShellHomeExit command →