LiveFire Labs: Online UNIX Training with Hands-on Internet Lab

"Taking a LiveFire Labs' course is an excellent way to learn Linux/Unix. The lessons are well thought out, the material is explained thoroughly, and you get to perform exercises on a real Linux/Unix box. It was money well spent."

Ray S.
Pembrook Pines, Florida

LiveFire Labs' UNIX and Linux Operating System Fundamentals course was very enjoyable. Although I regularly used UNIX systems for 16 years, I haven't done so since 2000. This course was a great refresher. The exercises were fun and helped me gain a real feel for working with UNIX/Linux OS. Thanks very much!"

Ming Sabourin
Senior Technical Writer
Nuance Communications, Inc.
Montréal, Canada

Read more student testimonials...

Receive UNIX Tips, Tricks, and Shell Scripts by Email

Custom Search

LiveFire Labs' UNIX Tip, Trick, or Shell Script of the Week

Processing Shell Script Options with the getopts Command

The getopts command simplifies the task of validating and parsing command line options and arguments for your shell scripts.  Without this built-in command, writing shell script code to perform these common tasks could quickly become a complex and lengthy undertaking.

The syntax for the getopts command is as follows:

getopts option-list variable

option-list contains valid options for the script, and variable is set to the option if it is found in option-list.  If the option is not in option-list, variable is set to the "?" character.

The following pet of code illustrates a basic implementation of the command:


PROG_NAME=$(basename $0)

while getopts abl: OPTION
    case ${OPTION} in
        a) A_FLAG=TRUE;;
        b) B_FLAG=TRUE;;
        l) LOGFILE=${OPTARG};;
      \?) print -u2 "Usage: ${PROG_NAME} [ -a -b -l logfile_name ]"
           exit 2;;

print ${A_FLAG}
print ${B_FLAG}
print ${LOGFILE}

There are a few key points you should understand about getopts and this example:

- getopts is designed to be executed inside of a loop, processing one option each iteration.  Once getopts processes the last option, it returns a non-zero value and the loop terminates.

- options requiring an argument ("l" in this example) need to be followed by a ":" (colon) on the getopts command line.

- option arguments are stored in the special variable OPTARG for script processing.

- if an invalid option is used, correct usage will be displayed and the script will exit with a return code of 2.

Here is a sample of the output for the above code (the script is named getopts_sample):

# ./getopts_sample -a -b -l testlog.txt

You may want to run the above code on your system to see what happens when an invalid option is used.

The previous has been a basic introduction to the getopts command.  A more detailed understanding can be obtained by reviewing your shell's man page.