For Loop in Shell Scripting

Issue

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 🙏

Solution

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

Answered By – Dan Bonachea

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published