"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."
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!"
getopts option-list variableoption-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.
#!/bin/ksh
PROG_NAME=$(basename $0)
A_FLAG=FALSE
B_FLAG=FALSE
while getopts abl: OPTION
do
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;;
esac
done
print ${A_FLAG}
print ${B_FLAG}
print ${LOGFILE}
- 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.Here is a sample of the output for the above code (the script is named getopts_sample):
- 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.
# ./getopts_sample -a -b -l testlog.txt
TRUE
TRUE
testlog.txt