I've been using getopts recently and I've set everything up. I've got a problem though. I want it to work so that if someone doesn't enter an argument on the command line, they get the help text, e.g.:
$ ./script
$ help: xyz - argument must be used.
Here's what I have at the moment.
#!/bin/bash
function helptext {
# ...
}
function mitlicense {
# ...
}
while getopts "hl" opt; do
case $opt in
h) helptext >&2
exit 1
;;
l) mitlicense >&2
exit 0
;;
\?) echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:) echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
*) helptext >&2
exit 1
;;
esac
done
You can get the number of arguments from the special parameter $# . Value of 0 means "no arguments". $# is read-only. When used in conjunction with shift for argument processing, the special parameter $# is decremented each time Bash Builtin shift is executed.
Command-line arguments are read in a positional manner, from position $1, $2, .. $n . The pattern $ followed by an integer is a reserved combination to represent the command-line arguments. $0 denotes the name of the script.
2. Argument List. Arguments can be passed to a bash script during the time of its execution, as a list, separated by space following the script filename. This comes in handy when a script has to perform different functions depending on the values of the input.
Validate user input using an if test such as below.
The -z
option of test
returns true if the length of the string which follows -z is zero.
if [ -z "$1" ]
then
helptext
exit 1
fi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With