notomera
notomera

Reputation: 81

For Loop in Shell Scripting

I am new to shell scripting, and I've recently encountered something I didn't comprehend.

What is the difference between these two scripts:

Script 1:

COLORS="RED YELLOW GREEN"
for i in $COLORS
do
echo $i
done

Script 2:

for i in "RED YELLOW GREEN"
do
echo $i
done

From my perspective, they should have the same output, but they don't. Output:

Script 1:

RED
YELLOW
GREEN

Script 2:

RED YELLOW GREEN

Thanks a lot 🙏

Upvotes: 1

Views: 1935

Answers (1)

Dan Bonachea
Dan Bonachea

Reputation: 2477

The difference comes down to quoting and variable expansion rules.

After variable expansion, the quotes in the first example are gone and this is equivalent to a loop over 3 elements:

for i in RED YELLOW GREEN
do
echo $i
done

whereas the second example is a loop over one element that happens to be a string containing spaces:

for i in "RED YELLOW GREEN"
do
echo $i
done

If you want to get the second behavior while using a variable, you need to add a level of quoting around the variable expansion, ie:

COLORS="RED YELLOW GREEN"
for i in "$COLORS"
do
echo $i
done

Upvotes: 1

Related Questions