Iterating options and quoted / unquoted arguments are passed to the bash script

I have a bash script that uses getopt to parse its parameters. It handles keys and long parameters correctly, as well as arguments and quoted arguments, but I can't figure out how to iterate over the options / arguments string returned by back windows. Something like:

params=`getopt -o ab -l ccc  -- "$@"`
echo $params
for param in "$params"
do
echo $param
done

      

Will exit -a -- 'foo' 'foo bar'

when the script is called as ./a.sh -a foo "foo bar"

, but the loop, rather than iterating separately, will only execute once across the entire line. Removing double quotes:

for param in $params

      

will make it repeat like this:

-a
--
'foo'
'foo
bar'

      

ignoring quotations around "foo bar". Is there an easy way to fix this?

+2


source to share


2 answers


From the getopt man page (at least util-linux one :)

Traditional implementations of getopt (1) cannot handle spaces and other (shell-specific) special characters in arguments and non-option parameters. To solve this problem, this implementation can generate quoted output, which must be interpreted by the shell again (usually with the eval command). This results in serving these characters, but you must call getopt in such a way that it is not longer compatible with other versions (second or third format in SYNTAX). A special test option (-T) can be used to determine if this extended version of getopt (1) can be used.

Example:



$ getopt -- 'abc' -a -b 'foo bar' -c
-a -b -c -- 'foo bar'

      

So you can see the output is quoted, ready to use:

$ eval set -- "`getopt -- 'abc' -a -b 'foo bar' -c`"
$ for a; do echo "arg: $a"; done
arg: -a
arg: -b
arg: -c
arg: --
arg: foo bar

      

+2


source


Take a look at the bash

built-in getopts

.



Also, getopt

see this script for a good usage example .

0


source







All Articles