Reputation: 11030
I have a simple question, I think, but I can't find the solution for it.
A simple perl script prints out following line "tests - Blub" "tests - Blub - Abc"
and I assign it to a variable like that var=$(perl ...)
, but why can't I parse it to an array with varArray=( $var )
and that command varArray=( "tests - Blub" "tests - Blub - Abc" )
works?
The expected result should be like this:
tests - Blub
tests - Blub - Abc
And not like this:
"tests
-
Blub"
"tests
-
Blub
-
Abc"
Thanks for any advices.
Upvotes: 1
Views: 219
Reputation: 1
How about using xargs in combination with sh -c '...' ?
line='"tests - Blub" "tests - Blub - Abc"'
printf '%s' "$line" | xargs sh -c 'printf "%s\n" "$@"' argv0
IFS=$'\n'
ary=( $(printf '%s' "$line" | xargs sh -c 'printf "%s\n" "$@"' argv0) )
echo ${#ary[@]}
printf '%s\n' "${ary[@]}"
Upvotes: 0
Reputation: 247022
Here's some doodling:
$ bash
$ a='"tests - Blub" "tests - Blub - Abc"'
$ ary=( $a ); echo ${#ary[@]}
8
$ ary=( "$a" ); echo ${#ary[@]}
1
$ eval ary=( $a ); echo ${#ary[@]}
2
Clearly the 3rd result is what you want. When you populate your variable from the output of the Perl script, the double quotes within it have no special meaning to the shell: they're just characters. You have to get the shell to parse it (with eval
) so that their meaning is exposed.
Upvotes: 2
Reputation:
I did the following:
$ cat >/tmp/test.sh
echo '"tests - Blub" "tests - Blub - Abc"'
$ chmod +x /tmp/test.sh
$ /tmp/test.sh
"tests - Blub" "tests - Blub - Abc"
$ a=`/tmp/test.sh`
$ echo $a
"tests - Blub" "tests - Blub - Abc"
$ arr=($a)
$ echo $arr[1]
"tests[1]
This tells me that () construct ignores double quotes after variable expansions. Moreover, when I do
for i in $a; do echo $i; done
I get a similar result:
"tests
-
Blub"
"tests
-
Blub
-
Abc"
Looks like quotes are handled before variable substitution takes place and not looked at again later.
Upvotes: 1