bash getopts - or how to gracefully error when encountering invalid arguments
I've been unable to find a way for getopts to gracefully handle spaces.
Code:
while getopts a:b:c o ; do Code:
./script.sh -a "one two" -b three four -c What I actually get is: Code:
varA=one two This has stumped me for quite some time now.. any help would be greatly appreciated. |
Quote:
From man bash: Code:
getopts optstring name [args] If you were to quote "three four", these would be seen as a single argument to -b, so it would then proceed to -c. |
I know that's how getopts works. I'm trying to either work around that, or, alternatively, work around user's failure to follow directions.
I think I just figured it out.. Code:
#!/bin/bash Code:
> ./x.sh -x "one two" -y -z three four -b edit: found the idea for the OPTIND workaround here. |
You would probably be better served then, to use GNU getopt (it isn't actually GNU but is known by that name).
It will canonicalize all the args and reorder them so that all non-option args come at the end of the list, no matter what order the user enters them, and offers some very useful error checking and additional options. (See man getopt as always). Something like this based on your original post using -a, -b and -c Code:
#!/bin/bash Code:
./mytest.sh -a "one two" -b three four -c |
Quote:
As this is a "quick-fix" to existing scripts, I'm going to leave the getopts in with this code in the functions that we need to error-check. I do, however, like that the GNU getopt code is cleaner, so will add an issue to our tracker for looking into a full re-vamp of the argument logic throughout the system. Thanks! |
All times are GMT -5. The time now is 01:51 AM. |