Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a bash variable to be a list of two word strings

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"
like image 591
Sam Avatar asked Oct 17 '25 03:10

Sam


1 Answers

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

like image 94
Charles Duffy Avatar answered Oct 19 '25 19:10

Charles Duffy