Saturday, March 12, 2022

[SOLVED] Reading a string of words into for loop from env file

Issue

I want to loop through a list of words like so:

words="hello world"
for w in $words; do
    echo $w
done

but I want the list of words (words="hello world") to come from a .env file placed in a directory and then reading the env file with export $(grep -v '^#' .env | xargs).

I am able to do the above however, the for loop is only looping through the first word, as if the whitespace in words is stopping the loop. Why is that?

I literally copied the variable from the .sh script into the .env file and it is not working the same way.


Solution

An easy solve is to separate words with comma instead of whitespace:

.env file

words=hello,world

script

Then the loop would work:

export $(grep -v '^#' .env | xargs)

for w in $words; do
    echo $w
done


Answered By - bcsta
Answer Checked By - Marilyn (WPSolving Volunteer)