3

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"
user8060686
  • 15
  • 1
  • 7
Sam
  • 1,765
  • 11
  • 82
  • 176
  • 2
    Why not use an array? – Inian May 24 '17 at 16:34
  • 2
    You're putting a list of strings into a string. Why not put a list of strings into a *list* -- or, rather, an array? – Charles Duffy May 24 '17 at 16:35
  • 1
    Related: [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050) -- strings can't be safely used to store lists for the same reason they can't be used to store commands. – Charles Duffy May 24 '17 at 16:36
  • @Inian Yeah that's the answer, I didn't know how to loop through arrays in bash, and I didn't know much about bash arrays in general – Sam May 24 '17 at 16:45

1 Answers1

10

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

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441