Is there a way in Bash (without calling a 2nd script) to parse variables as if they were command line arguments? I'd like to be able to group them by quotes and such.
Example:
this="'hi there' name here"
for argument in $this; do
echo "$argument"
done
which should print (but obviously doesn't)
hi there
name
here
Don't store the arguments in a string. Arrays were invented for this purpose:
this=('hi there' name here)
for argument in "${this[@]}"; do
echo "$argument"
done
It is highly recommended that you use this approach if you have control over this. If you don't, that is even more reason not to use eval, since unintended commands can be embedded in the value of this. For example:
$ this="'hi there'); echo gotcha; foo=("
$ eval args=($this)
gotcha
Less nefarious is something as simple as this="'hi there' *". eval will expand the * as a pattern, matching every file in the current directory.
I worked out a half-answer myself. Consider the following code:
this="'hi there' name here"
eval args=($this)
for arg in "${args[@]}"; do
echo "$arg"
done
which prints the desired output of
hi there
name
here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With