20

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 "
a
b
c";
do
 echo "test "$i
done

But that only outputs one string:

test a b c

How would I get this?

testa
testb
testc

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

5
  • Where are you getting the abc list from? A file? Typing it directly? Standard input?
    – jw013
    Nov 5, 2012 at 21:41
  • i want to create a script and have this in the clipboard
    – rubo77
    Nov 5, 2012 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, 2012 at 21:57
  • I understand your question. you want me to improve the question itself... i edited it now
    – rubo77
    Nov 5, 2012 at 22:03
  • Why noone mentioned tr " " "\n"
    – Luka
    Apr 18, 2018 at 14:51

2 Answers 2

25

You'd use a while loop instead.

while read i
do
  echo "test$i"
done <<< 'a
b
c'
1
  • 3
    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 Nov 10, 2015 at 16:50
23
export a="
a
b
c
"

for i in $a; do echo "test$i";done
8
  • 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, 2012 at 22:00
  • 1
    this solves it too: for i in $(echo "a b c"); do echo "test$i";done
    – rubo77
    Nov 5, 2012 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, 2012 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? Nov 5, 2012 at 23:31
  • 2
    If the string lines have spaces in between the characters, the for loop may not work as you desire.
    – cgseller
    Mar 27, 2019 at 19:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .