function readArgs() {
while getopts "i:o:p:s:l:m" OPTION; do
case "$OPTION" in
i)
input="$OPTARG"
;;
o)
output="$OPTARG"
;;
...
esac
done
}
readArgs
if [[ -z "$input" ]]; then
echo "Not set!"
fi
This is always giving me Not set!
but if I comment out the lines function readArgs() {
, }
and readArgs
, it works. Why?
Also,
input="$OPTARG"
echo "$input"
;;
does not work.
Normally, getopt is called in a loop. When getopt returns -1 , indicating no more options are present, the loop terminates. A switch statement is used to dispatch on the return value from getopt . In typical use, each case just sets a variable that is used later in the program.
Updated: 02/01/2021 by Computer Hope. On Unix-like operating systems, getopts is a builtin command of the Bash shell. It parses command options and arguments, such as those passed to a shell script.
getopt vs getopts The main differences between getopts and getopt are as follows: getopt does not handle empty flag arguments well; getopts does. getopts is included in the Bourne shell and Bash; getopt needs to be installed separately.
getopts
is parsing the arguments to the readArgs
function, and you're not giving that function any arguments.
Try with:
readArgs "$@"
getopts
relies on the OPTIND
variable being initialized to 1. Either do
readArgs() { OPTIND=1; ...
or
readArgs() { local OPTIND; ...
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