I have a bash script that uses getopt to parse its parameters. It correctly handles switches and long options, as well as arguments and quoted arguments, but I cannot figure out how to iterate over the options/arguments string returned by the backticks. Something like:
params=`getopt -o ab -l ccc -- "$@"`
echo $params
for param in "$params"
do
echo $param
done
Will echo out -a -- 'foo' 'foo bar'
when the script is invoked as ./a.sh -a foo "foo bar"
, but the loop rather than iterating over each separately will only run once over the entire string. Removing the double quotes:
for param in $params
will cause it to iterate like this:
-a
--
'foo'
'foo
bar'
ignoring the quoting around "foo bar". Is there a simple way to fix this?
Take a look at the
bash
builtingetopts
.Also, for a nice example of using
getopt
, see this script.From the getopt manpage (at least the util-linux one:)
Example:
So, you can see the output is quoted, ready to be used: