30

How do I inline an array of strings in a bash for loop ? This works:

array=(one two)
for i in ${array[*]};do echo $i; done

But I'd like to eliminate the extra local variable. I've tried many variations that seem reasonable, for example:

for i in ${("one" "two")[*]};do echo $i; done

or

for i in ${"one" "two"};do echo $i; done

In each case, it treats one and two as commands :(

Gene
  • 46,253
  • 4
  • 58
  • 96
expert
  • 29,290
  • 30
  • 110
  • 214

2 Answers2

31

Did you try with:

for i in "one" "two"; do echo "$i"; done

Alija Bevrnja
  • 411
  • 4
  • 6
  • 1
    That wouldn't be an array. – bufh Mar 20 '16 at 10:10
  • 1
    Sorry...I actually deviated from the question because I got the impression from: http://stackoverflow.com/questions/8880603/loop-through-array-of-strings-in-bash-script, that this functionality was being sought for (the current question asker commented there). I disregarded an option that one might want to reference another array element (not only the current one) in the body of the loop...should I remove the answer? – Alija Bevrnja Mar 20 '16 at 11:12
  • Even if it doesn't answer the question in its strictest interpretation, this answer was useful for me, and is probably for many who arrive here, judging by the upvotes. – trollkotze Oct 25 '20 at 08:54
  • is the implication here that it is simply impossible to inline an array in Bash? – user1034533 Jun 21 '22 at 18:00
12
for i in {one,two}; do echo "$i"; done
J.O.L.
  • 141
  • 1
  • 4
  • I couldn't make it work until I realized you that you can't have a space into `{"some text", "test"}`. For anyone else getting stuck, make sure you don't have a space after any commas inside `{...}` – antshar Oct 19 '22 at 12:34