I'm trying to run a for loop over a list of strings where some of them are quoted and others are not like so:
STRING='foo "bar_no_space" "baz with space"'
for item in $STRING; do
echo "$item"
done
Expected result:
foo
bar_no_space
baz with space
Actual result:
foo
"bar_no_space"
"baz
with
space"
I can achieve the expected result by running the following command:
bash -c 'for item in '"$STRING"'; do echo "$item"; done;'
I would like to do this without spawning a new bash process or using eval
because I do not want to take the risk of having random commands executed.
Please note that I do not control the definition of the STRING variable, I receive it through an environment variable. So I can't write something like:
array=(foo "bar_no_space" "baz with space")
for item in "${array[@]}"; do
echo "$item"
done
If it helps, what I am actually trying to do is split the string as a list of arguments that I can pass to another command.
I have:
STRING='foo "bar_no_space" "baz with space"'
And I want to run:
my-command --arg foo --arg "bar_no_space" --arg "baz with space"
STRING
is not a list of quoted strings; it is a single string. In that string, quotes have no more meaning than any other character. – Steerebash -c '...'
is no safer thaneval
; you are still executing arbitrary code. – Steerebash -c '...'
will execute the code. Basically I was hoping bash would expose a way to parse the string the way it does internally (because it must do it somehow) but without all the other interpreting features. I guess there is no such thing and I must use a parsing approach outside of bash. I don't really understand all the negative votes though. Are people juste voting down because there is no answer ? – Twombly