Bash Concatenate String in Loop Results in Empty String

Bash Concatenate String in Loop Results in Empty String

I have the following file

Hello
World
my
name
is
FalcoGer

And I wish to concatenate the strings of each line.

I wrote the following script to do just that.

#! /usr/bin/bash
myFile=/home/FalcoGer/testfile.txt

result=""
cat $myFile | while read line
do
  result+="$line "
done

echo Result: $result

However I only get Result: with an empty string. When I print it from within the loop it seems to work just fine. What's wrong with this script and how do I fix it?

8

1 Answer

Using the pipe essentially creates a new script with a new scope. You can avoid the pipe like so:

#! /usr/bin/bash
myFile=/home/FalcoGer/testfile.txt

result=""
while read -r line
do
  result+="$line "
done < $myFile

echo Result: $result
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.