It's always a good idea to add a usage clause at the start of any but the most simplest scripts. This will help users run the script correctly. Here's an example:

#!/bin/bash
# Rename files depending on input

usage () {
  echo "Usage: $0 new | old"
    exit 1
}

# Check input is valid i.e. one argument either old or new
if [ $# -ne 1 ]
then
  usage
else
  if [[ $1 != "new" && $1 != "old" ]]
  then
    usage
  fi
fi

ANSWER=$1
...rest of the script

The script starts with a function that just echoes how to use the script, $0 resolves as the script name and it expects yes or no as an argument. This function is called a couple of times in the logic that follows (which is why a function is better than hard coding the message in the function).

The script then checks the number of arguments, $# and if it's not equal to one, calls the usage function and exits, i.e. the script expects one arguement only. If there is one argument, it then checks if the arguement is either yes or no. Again, usage is called and the script exits if the supplied arguement isn't yes or no. Finally, the arguement supplied, which equates to $1 is set to variable $ANSWER. The script then continues.

Response examples:

 $ ./rename_new_files.sh
 Usage: ./rename_new_files.sh new | old
 $ ./rename_new_files.sh maybe
 Usage: ./rename_new_files.sh new | old
 

In the first example, no arguement is supplied, so you get the usage message, then the wrong arguement is supplied with the same result.

Recent Changes

Contribute to this wiki

Why not help others by sharing your knowledge? Contribute something to this wiki and join out hall of fame!
Contact us for a user name and password