1

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.

1
  • 2
    First don't use upper case variables names if it is just internal to your script since envrionmental and bash internal variables are upper cased. Put an 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. Commented Apr 4, 2021 at 18:40

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

>Just do not use cat - ie. do not use pipe Using the pipe essentially creates a new script with a new scope.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.