Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading