0

Having this odd issue with a simple bash script:

#!/bin/bash

function printLinesFromInput {
    COUNTER=1
    while read USER; do 
        echo "Hello $USER"; 
        echo
    done < $1
}

while read USER; do 
    echo "Hello $USER"; 
done < south-park.txt

echo
echo "In function:"
echo $(printLinesFromInput south-park.txt)

It prints:

$ ./readFile.sh
Hello Eric
Hello Kyle
Hello Stan
Hello Kenny

In function:
 Hello Kenny

The function is not echoing all four lines of the file. I am wondering why is this the case. The input file south-park.txt is:

Eric
Kyle
Stan
Kenny
1
  • I gave this a shot, but was not able to reproduce your problem on Bash 4.4.12 in Cygwin; the "in function" output was Hello Eric Hello Kyle Hello Stan Hello Kenny as expected (on one line because of $()). Commented Mar 7, 2018 at 6:53

1 Answer 1

1

I suppose the input file south-park.txt may contain CR LF line breaks. Try to say:

 ./readFile.sh | less

Then you'll see:

Hello Eric
Hello Kyle
Hello Stan
Hello Kenny

In function:
Hello Eric^M Hello Kyle^M Hello Stan^M Hello Kenny

To fix it, remove \r's in your input file or modify the function as:

function printLinesFromInput {
    COUNTER=1
    while read USER; do
        echo "Hello $USER" | tr -d '\r'
    done < $1
}

BTW if you want to insert line breaks between users, you'll need another trick :-).

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

Comments

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.