Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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)

share|improve this question
    
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

3 Answers 3

up vote 2 down vote accepted
export a="
a
b
c
"

for i in $a; do echo "test$i";done
share|improve this answer
    
thanks, that was what I needed –  rubo77 Nov 5 '12 at 21:55
    
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

You'd use a while loop instead.

while read i
do
  echo "test$i"
done <<< 'a
b
c'
share|improve this answer
    
this works too, thanks –  rubo77 Nov 5 '12 at 21:57

bash has a built in ability to do this with the curly brackets, that way you dont have to list out all your letters you want to use.

for i in {a..c}; do echo "test $i"; done
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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