Shell Script Writing - Select and Getopts
(Page 3 of 4 )
The select structure will offer you the chance to make a little interactive script. With this, you can ask the user to select a route to follow in the script. The shell will take care of printing a list of the options, followed by a prompter character. The prompter character is what is inside the PS3 variable.
The user will then have to select an option by entering the number of the corresponding line (the number of lines will be also printed). Then the option that you just entered will be inside a variable. Inside the select structure, you may work with this variable. The syntax is:
select variable in list
do
#here you can enter commands
# in the variable you will have the entered option
done
With the example:
PS3="~>"
select alfa in Avril Hilary Kelly
do
echo Your option was $valtozo
# possible output: Your option was Avril
break
#unless you break out the shell will start over again
done
This is great if you want to set options on the fly. However, sometimes the user already knows what options he wants, and he may specify the options right from the start. This way, the scripts you write more closely resemble UNIX tools, and the user will need zero learning time with them. In an effort to make this as simple as possible, the getopts command was made:
getopts option_string variable
In the option_string, you need to enumerate the options, and where an argument is expected for the option, you have to add a : symbol. We will call the function multiple times. Every time it will return a true statement, as long as there are more options on the command line for the script.
In addition, the command will set two variables. The $OPTIND will be the number of the argument at which it arrived. The $OPTARG will be the argument to the option. Most of the time you would like to combine it with the while loop to treat every option.
#!/bin/bash
#first set the option flags and takes care of the options
while getopts "x:y:zr" option
do
echo $OPTIND
echo $OPTARG
case $option in
#list the content of the argument
x) ls $OPTARG;;
#set this opt. on whit the argument
y) optionY=$OPTARG;;
z) echo Option Z was selected;;
r) verbose=1; echo Verbose mode on;;
?) echo $option is not a valid option
esac
done
...#follows the execution of script further
Next: Putting it all together >>
More Miscellaneous Articles
More By Gabor Bernat