For an script I'm making I need to convert the output of a command to an array. For simplifying I have made an example using echo:
arr=( $(echo '"test example" "test2 example"') )
What I want is the first element of the array to be
test example
but when doing this:
echo ${arr[0]}
I get
"test
What I have to do to get the result I want?
echo
there. What you can do isarr=("test example" "test2 example"); echo "${arr[0]}"
. This is how you create an simple array in bash.eval
method suggested in an answer is dangerous since the output of the command will be evaluated — whatever controls the output of that command can cause your script to run whatever program they want) and the definition is ambiguous (e.g. can you have a"
in an element? how? What do you do if the output doesn't contain balanced quotes? …)."word word" "word word"
(...) It outputs two words with a space in the middle of them surrounded by quotes and each one of these separated by spaces. If there are quotes they are escaped\"
. The eval as you and @ilkkachu said has risks. I might look into either changing the program I execute if I can or making my own replacement so the output can be more easily used, maybe using mapfile.