1

I have an example string:

echo $ExampleString
"Hello World" var2 var3

How can I split the string to be separate variables?

Desired outcome:

echo ${ExampleStringArray[0]}
Hello World

echo ${ExampleStringArray[1]}
var2

echo ${ExampleStringArray[2]}
var3
2
  • Does the variable contain the literal double quotes around Hello World? Commented Jan 30, 2020 at 1:08
  • Yes it does, this is the part that made me seek help! Commented Jan 30, 2020 at 1:10

1 Answer 1

1

You can use eval to create an array:

eval ExampleStringArray=($ExampleString)

Which will create:

declare -a ExampleStringArray=([0]="Hello World" [1]="var2" [2]="var3")

Although you should be wary if the variable contains any potential commands or special characters.

1
  • 1
    So simple and clean. Appreciate the introduction to eval. Commented Jan 30, 2020 at 1:22

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.