Hello again. It has been some time since I have posted here. Bash is the focus of todays post. Well… Really it is the focus of several posts over the next few weeks as we delve into some best(ish) practices when writing bash scripts. The culmnination of these articles will be the creation of a bash script template file that can be used to make writing scripts a little faster/better.
Enter getopts… We will start with some code then break it down.
<code># Loop through $@ to find flags
while getopts ":hs:e:" FLAG; do
case "${FLAG}" in
s) # Here lies some flag
OPTION1="${OPTARG}" ;;
e) # Another flag, we will call this one fred
FRED="${OPTARG}" ;;
h) # A flag with no value
HELP=1
echo "You need some help. We will get to that later." ;;
esac
done
</code>
Let’s break it down…
<code>getopts ":hs:e:" FLAG
</code>
The format of getopts is
<code>getopts OPTSTRING VARNAME
</code>
Where:
OPTSTRING - is what getopts should expect as an option and whether to expect an argument to that option. It also allows the specification of how to deal with errors.
VARNAME - is used to report back the option that was found.
Options are specified as simply the character you are looking for(sorry no long options supported). If you want to retreive the argument immediatly following the flag, you may place a : after the option.
Error handling defaults to verbose and can be switched to silent by preceding the OPTSTRING with a :
In the event of an error, VARNAME will be set to ? to indicate an invalid option and : to indicate that a required argument was not found.
getopts is usually run in a while loop so that it can process all of $@.
<code>case "${FLAG}" in
</code>
A case statement is used to evaluate which optino we are dealing with, although you could use if/then if you so chose.
<code>s) # Here lies some flag
OPTION1="${OPTARG}" ;;
e) # Another flag, we will call this one fred
FRED="${OPTARG}" ;;
h) # A flag with no value
HELP=1
echo "You need some help. We will get to that later." ;;
</code>
You can perform whatever operations you want based on the option chosen, although it is common to either set a variable or run a function such as print_usage.
How do we put this together into something useful?
<code># ./foo -h
You need some help. We will get to that later.
# ./foo -s hello
hello world
# ./foo -s
# ./foo -s goodby
#
</code>
For more information see http://wiki.bash-hackers.org/howto/getopts_tutorial
Have fun…
Bash Best(ish) practices part 4 Bash Best(ish) practices part 3 Bash Best(ish) practices part 2