Once a bash program is executed while processing options in getops
, the loop exits.
As a short example, I have the following bash script:
#!/usr/bin/env bash
while getopts ":a:l:" opt; do
case ${opt} in
a)
ls -a $2
;;
l)
ls -l $2
;;
\?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument" >&2
exit 1
;;
esac
done
echo -e "\nTerminated"
If the script is called test.sh
, when I execute the script with this command, I get the following output, where only the -a
flag is processed, and -l
is ignored:
$ ./test.sh -al .
. .. file1.txt file2.txt test.sh
Terminated
However, if I remove the colons after each argument, indicating that operands are not required for each argument, then the script does as intended. If the while
loop is changed to:
while getopts ":al" opt; do
Then, running my script gives the following output (with both -a
and -l
processed):
$ ./test.sh -al .
. .. file1.txt file2.txt test.sh
total 161
-rwxrwxrwx 1 root root 0 Nov 24 22:31 file1.txt
-rwxrwxrwx 1 root root 0 Nov 24 22:32 file2.txt
-rwxrwxrwx 1 root root 318 Nov 24 22:36 test.sh
Terminated
Additionally, adding something like OPTIND=1
to the end of my loop only causes an infinite loop of the script executing the first argument.
How can I get getopts
to parse multiple arguments with option arguments (:
after each argument)?