Can getopts arguments be combined with other input?
3
votes
2
answers
3628
views
I am writing a script that would take a string as input along with other options the user can select by using arguments as indicators. So in other words, something like this:
./script "My input string" -pxz
or
./script -pxz "My input string"
But I run into the following issue. It seems the getopts command stops working after a non-getopts-style argument is entered. Check this out, for example:
#!/bin/bash
while getopts "ab" arg; do
echo $arg received
done
When we run it we get:
$ ./example.sh -a -b -a string -b
a received
b received
a received
$
It stops at "string" and won't continue. The getopts command returns a nonzero exit status because "string" is not the kind of argument it expects to read, and the while loop ends. I've tried adding a second
while getopts
but that doesn't do anything. The "read head" of getopts is still stuck on that "string" argument and will simply exit with a nonzero exit status again.
What this means is that seemingly, I wouldn't be able to have the user enter their string first and then the options, because getopts would never be able to read past the string and get there. So I can't do this:
./script "My input string" -pxz
On the other hand, if I told the user to enter first their options and then the string I'd have the problem of figuring out how to retrieve the string. Normally, if there were no options, I'd do this:
string="$1"
But now since there are options and I don't know how many there are, I no longer know what position the string occupies. So how would I be able to retrieve it?
Now, ideally my script should actually be able to work in both of those ways or even a combination of the two. It should be able to handle input like:
./script -p "My input string" -xz
So how can I go about resolving this issue?
Asked by Isaac D. Cohen
(243 rep)
Aug 9, 2022, 09:02 PM
Last activity: Nov 1, 2023, 05:20 PM
Last activity: Nov 1, 2023, 05:20 PM