1

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 🙏

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.