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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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