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?
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?
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
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
*
, you get quite a different output. – Kusalananda May 20 '20 at 16:41'
will have literally what it holds right... – Stalin Vignesh Kumar May 20 '20 at 16:51