First, please use
[code][/code] tags around your code, to preserve formatting and to improve readability.
Next, it's vitally important to understand the way bash handles arguments, whitespace, and word-splitting. Don't do anything else until you've finished reading this page:
http://mywiki.wooledge.org/Arguments
Now that that's out of the way, a
for loop works on lists of words (as defined by the shell's word-splitting operation). Each element is taken into the variable in turn, and the subsequent operations performed. So if you don't quote the input variable, then it will split it into individual words wherever there's whitespace (by default at least). But if you do quote it, it will treat the whole thing as a single block. Neither option does exactly what you want.
Therefore, when you want to operate on lines, you should use a
while+read loop instead (as demonstrated by T3slider). The
read command grabs whole lines of input (by default), so you don't have to worry about shell word-splitting occurring on other whitespace.
I would, however, use a
here string to take input from a variable, rather than process substitution, as it doesn't require running a subshell.
Code:
while read num; do
echo "$num"
done <<<"$numbers"
Finally, a
variable is designed to hold an individual string of characters. When you have multiple strings to work on (strings of strings), you should generally use an
array instead. Set each array element to hold one line, and you can go back to using a for loop, and call on the array's index numbers to manipulate the individual elements.
Code:
numbers=( one two three four )
for i in 0 2 ; do
echo "${numbers[i]} ${numbers[i+1]}"
done
When you have the time, read through this guide in its entirety. It will teach you pretty much all the background concepts you need to know for good bash scripting:
http://mywiki.wooledge.org/BashGuide