abc xyz
abc xyz

Reputation: 129

Concatenating a string inside a while loop in bash

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.

Upvotes: 1

Views: 2990

Answers (1)

KamilCuk
KamilCuk

Reputation: 140880

Just do not use cat - ie. do not use pipe. And do not use USER.

while read var; do
        str="${str}${var}"
done < "$file"

Do not use upper case variables in your scripts. USER is variable set by bash to the name of current user.

Check scripts with http://shellcheck.net

Read https://mywiki.wooledge.org/BashFAQ/024

Read https://mywiki.wooledge.org/BashFAQ/001

Do not uselessly use cat.

In bash you can also use str+="$var".

Quote variable expansions.

Upvotes: 3

Related Questions