I want to assign a bash variable to be a collection of two word segments. The bash variable is similar to a list of strings, where each string is two separate words enclosed within quotation marks). I am then trying to use this variable within a for loop so that the loop variable is assigned to one of the two word segments each iteration.
Here is my code:
#!/bin/bash
variable='"var one" "var two" "var three"'
for i in $variable
do
echo $i
done
The output I would like is :
var one
var two
var three
But what I am getting at the moment in
"var
one"
"var
two"
"var
three"
Define a single three-element array, not a 31-character string:
variable=(
"var one"
"var two"
"var three"
)
for i in "${variable[@]}"; do
echo "$i"
done
If you need to accept a string as input and parse it into an array while honoring quotes in the data, we have other questions directly on-point; see for instance Bash doesn't parse quotes when converting a string to arguments
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.