1

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!

skwidbreth
  • 7,888
  • 11
  • 58
  • 105

1 Answers1

5

By putting the read loop in a pipe, you are building the string in a subprocess. Instead, do something like:

#!/bin/bash

some_string=""

while read line; do 
    some_string+="$line"
done < .env

echo "$some_string"

But, really, don't do any of that. Instead, do:

some_string=$(tr -d \\n < .env)

It's worth noting that sometimes you want to keep the subprocess, but you need to be aware that the variables will lose their values at the end of the process. But it is sometimes very convenient to do things like:

#!/bin/bash

some_string=""

cmd | {
    while read line; do 
        some_string+="$line"
    done 
    echo "in pipe, some_string=$some_string"
}
echo "after pipe, some_string=$some_string"
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • Nailed it! Thanks, William. Having little experience with shell scripting, I was't familiar with the fact that this would handle it in a subprocess. Good learning, much appreciated. – skwidbreth Dec 06 '20 at 17:12