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.
CodePudding user response:
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
CodePudding user response:
Using str_split() -- which converts a string into an array of characters -- and a foreach loop should solve this.
Try: foreach(str_split($words) as $w){ echo $w . "\n"; }