I need to create a script with a loop through a list of items. I want to insert a string in the script.

I tried:

for i in "
 echo "test "$i

But that only outputs one string:

test a b c

How would I get this?


(a, b and c are just examples for some longer words, which I got from an OpenOffice Calc file)

  • Where are you getting the abc list from? A file? Typing it directly? Standard input? – jw013 Nov 5 '12 at 21:41
  • i want to create a script and have this in the clipboard – rubo77 Nov 5 '12 at 21:55
  • And how do you plan to access this "clipboard" from the script? Pasting into standard input? Using something like xclip? – jw013 Nov 5 '12 at 21:57
  • I understand your question. you want me to improve the question itself... i edited it now – rubo77 Nov 5 '12 at 22:03
  • Why noone mentioned tr " " "\n" – Luka Apr 18 '18 at 14:51
export a="

for i in $a; do echo "test$i";done
  • I just wonder, what's the difference to my script? why do you need to put the string in a variable $a first? – rubo77 Nov 5 '12 at 22:00
  • this solves it too: for i in $(echo "a b c"); do echo "test$i";done – rubo77 Nov 5 '12 at 22:04
  • 2
    @rubo77 The difference is the $a is unquoted, meaning that it undergoes word splitting, whereas "a b c" is quoted, so the shell sees it as all one word. – jw013 Nov 5 '12 at 22:05
  • 2
    Note that it undergoes work splitting and filename generation. Also, the "export" doesn't make sense here. What's wrong with for i in a b c; do echo "test$i"; done? – Stéphane Chazelas Nov 5 '12 at 23:31
  • @StephaneChazelas you're right, export is not needed within the script- – Bonsi Scott Nov 6 '12 at 5:35

You'd use a while loop instead.

while read i
  echo "test$i"
done <<< 'a
  • 2
    For the curious, this is called a "here string", which is a variant of "here documents", which use two less-than signs and a delimiter at the end and beginning of the content – Hanno Fietz Nov 10 '15 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.