I am trying to write a program in bash which takes as input argument a file name and then takes every line of that file and appends it to a string. At the end, I want to print this string. This is what I wrote (consider that the program name is concat.sh):
#!/bin/bash
FILE=$1
STR=""
cat $FILE | while read USER; do
STR="${STR}${USER}"
done
echo "$STR"
And I have the file stuff.txt, which has the following:
a
b
c
And after I run ./concat.sh stuff.txt I get the empty string. I tried multiple variations of that concatenation, with space, without space (like above), with newline, etc. Still doesn't work. If I try to simply print each line, it works. So if I simply add the line echo "$USER" inside the loop I get the correct output, i.e., a, b, c (each on a different line). But that string concatenation still doesn't work. It doesn't work even if I stop using that $USER variable in the concatenation. So if I do something like STR="${STR} abc" the characters abc are surprisingly not concatenated to STR. But if I take this outside of the while loop it actually works (so if I comment the while loop and simply do STR="${STR} abc" I will get abc in the string STR). I am a newbie in bash and this looks like really weird behaviour to me and have no idea what is going on/how to fix it.
echo "$USER"after the shebang of your script and run it, to confirm it. Have a look at mywiki.wooledge.org/BashFAQ/024 for the issue your having. Also paste your script at shellcheck.net for more validation.