1

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.

0

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

4 Comments

That is my problem I am facing to and I don't know how to fix it, because I don't want to switch the language.
I hate to say this, but using arrays in Bash is probably a sign you need a more capable language...
There is a solution with eval see the other answer.
Ouch. Be careful with $, ` and other characters meaningful inside "".
0

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[@]}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.