25

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
  • 44,980
  • 4
  • 53
  • 91
expert
  • 28,066
  • 28
  • 108
  • 205

2 Answers2

27

Did you try with:

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

Alija Bevrnja
  • 371
  • 3
  • 5
  • 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
10
for i in {one,two}; do echo "$i"; done
J.O.L.
  • 121
  • 1
  • 4