Database Reference
In-Depth Information
Shell Getopts Command
In addition to getopts (plural), Linux has a getopt (singular) command. This discussion is about getopts . This is a
shell utility, not an EM CLI verb. The previous example prompted the user for two department numbers, which is fine
for interactive scripts but isn't scalable for scheduled jobs. You could use positional parameters at the command line,
like this:
if [ $1 ]; then
export OLD_DEPT=${1}
else
read OLD_DEPT?"Enter the old department number: "
fi
if [ $2 ]; then
export NEW_DEPT=${1}
else
read NEW_DEPT?"Enter the new department number: "
fi
if [[ ${OLD_DEPT} == ${NEW_DEPT} ]]; then
echo "The values for the old and new departments are the same"
< Error handling >
fi
This approach relies on user inputs being presented in the correct order. In the current example, the first input
value corresponds to the old department and the second to the new department. What if they aren't in the right order,
however? The getopts command allows you to use input flags to avoid this problem.
Command-line input is evaluated by a case statement in your script that determines how flag values are to be
handled. The order they were entered on the command line is irrelevant. OPTARG is the name of the value passed by
getopts . Let's look at how that works. For this entry on the command line, a string will be returned via the getopts
output named OPTARG .
./change_admin_depts.sh -a 500 -b 750
while getopts a:b: OptValue; do
case $OptValue in
a) export OLD_DEPT=${OPTARG};;
b) export NEW_DEPT=${OPTARG};;
*) echo "No values were provided for old and new departments";;
esac
done
This example tested a temporary variable named OptValue against expected characters and responded
accordingly. Each value identified as an -a or -b on the command line set corresponds to a value for a new or old
department number.
echo $OLD_DEPT
500
echo $NEW_DEPT
750
 
Search WWH ::




Custom Search