Create usage messages
From Linux Shell Scripting Tutorial - A Beginner's handbook
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:
gccSample outputs:
gcc: no input files
Try rm command:
rmSample 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 userlookup.sh:
#!/bin/bash # 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 passwddb=/etc/passwd # 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 userlookup.sh ./userlookup.sh
Sample outputs:
Usage: ./userlookup.sh username
Pass the command line argument kate:
./userlookup.sh kateSample outputs:
kate not found
Pass the command line argument vivek:
./userlookup.sh vivekSample outputs:
vivek found