Don't worry much
Preface
if/case Conditional Statements
while Loops
Using test To Check true/false stuff
Using Variables
Writing Functions
Begin!
First of all, let's review what our sample script has to do: it accepts two parameters, each of them prints a different sentence. If there are any other unknown parameters other than what we wanted or no parameters given, print the usage message.
First, we write a basic function which prints the help message when called, and then check the number of parameters given and see if it is zero:
#!/bin/bash
function help {
echo "Usage: test -p"
}
if test $# -eq 0; then
help
exit 0
fi
exit 0
OK, test and run! if you don't give any parameters, it prints the help message. But... what about checking the parameter itself? Thats where getopts comes into play! First of all, look at the following script, which adds the getopts to the above script:
#!/bin/bash
function help {
echo "Usage: test -p"
}
if test $# -eq 0; then
help
exit 0
fi
while getopts "p" option; do
case $option in
p) echo "this is a test";;
*) help;;
esac
done
exit 0
How It Works?
Each time the while loop is executed, getopts puts the next parameter into the variable option. The parameters desired, must be defined as a string, containing them one by one. For example, if you want to accept the parameters a, b, and c, the loop should be:
while getopts "abc" var; do
case $var in
a) echo "parameter a given";;
b ) echo "parameter b given";;
c) echo "parameter c given";;
*) echo "Usage: script -abc";;
esac
done
See how easy it is? now, what about the arguments for each parameter?
Accepting Arguments
getopts gives you a way to accept arguments for a parameter too! Just put a : after the parameter's name. Like this:
while getopts "a:bc" var; do
case $var in
a) echo "parameter a given, it's argument is $OPTARG";;
b ) echo "parameter b given";;
c) echo "parameter c given";;
*) echo "Usage: script -a message -bc";;
esac
done
As understood from above script, the corresponding argument for a parameter is inside the variable OPTARG. So, you can easily manage it
Wrong Parameters
If a user gives your script unexpected parameters, for example -f in above script, getopts automatically prints a message stating wrong parameter given, some times it is useful. But if you don't want to receive such message and handle things yourself with a nicer way, you can tell getopts to suppress these kind of messages, by putting a colon at first of parameter definition. Like this:
while getopts ":a:bc" var; do
case $var in
a) echo "parameter a given, it's argument is $OPTARG";;
b ) echo "parameter b given";;
c) echo "parameter c given";;
*) echo "Usage: script -a message -bc";;
esac
done
This, was a way to parse basic parameters and arguments. If you like to work with parameters like -param, getopts is not the way to do it. So you have to implement it yourself
Hope this tutorial helped you get started and ready to accept parameters







MultiQuote


|