1

If I run this:

abc="one
two
three"
for item in "$abc"; do echo "Item: $item"; done

I get:

item: one
two
three

But I was expecting:

Item: one
Item: two
Item: three

What am I doing wrong?

terdon
  • 242,166

2 Answers2

2

You are passing the variable quoted, which means it will be treated as a single argument. You would get the output you expect if you simply left it unquoted (note that this can cause various other problems):

$ for item in $abc; do echo "Item: $item"; done
Item: one
Item: two
Item: three

However, why use a string when what you want is a list of values? That's what arrays are for (assuming you are using bash):

$ abc=(one two three)
$ for item in "${abc[@]}"; do echo "Item: $item"; done
Item: one
Item: two
Item: three

Or, if you're not using a shell that can understand arrays, do:

$ abc="one           
two
three"
$ printf '%s\n' "$abc" | while read -r item; do echo "Item: $item"; done
Item: one
Item: two
Item: three
terdon
  • 242,166
0

Just remove the "" for variable $abc to expand it what it holds.Double quoting it will remove new lines in white space

$ abc="one                                     
two
three"


$ for item in $abc; do echo "Item: $item"; done
Item: one
Item: two
Item: three
  • Not quite "literally what it hold". The shell would split the values on spaces, tabs and newlines, and then do filename globbing on the generated words, so if one of the words is e.g. *, you get quite a different output. – Kusalananda May 20 '20 at 16:41
  • Yes , it will list the files in current directory , you are right .I meant it will expand first and holds it...singe ' will have literally what it holds right... – Stalin Vignesh Kumar May 20 '20 at 16:51