In my bash script, I'd like to read the contents of a file and append each line of the file to an empty string via a loop. This seems like it would be easy to do and I thought I had implemented it correctly based on some other posts on SO (like Concatenate inputs in string while in loop), but the end result still seems to be an empty string. I'm clearly doing something wrong, but I'm not very experienced with bash scripting so I could use a quick hand.
My bash script:
#!/bin/bash
SOME_STRING=""
cat .env | while read line
do
SOME_STRING+="$line"
done
echo "$SOME_STRING"
and the .env
file it references:
FOO=bar
BAZ=bim
I'd expect the output to be FOO=barBAZ=bim
, but it just writes an empty string. If I toss an echo "$SOME_STRING"
inside of the loop, I do see the string building up as expected, though.
I'm going to assume that this has something to do with the way that I'm reading the file contents and/or looping through it - for example, I tried a for
/in
loop through a space-separated string instead of a while
loop through the file contents, and that worked fine.
Thanks much!