While loop read line not working

Hi,
I am trying to read a file line by line inside of a while loop. This while loop is part of a here document.

while read  line
do
  ssh -t $2@$remotehost  <<REMOTE

   ls path/to/dir > $path_to_dir

    while read line1
        do
                echo "LINE --- $line"
        done <$path_to_dir

REMOTE
done < "$filename"

The problem here is.
$path_to_dir has 3 lines.
echo "LINE ----" is printed 3 times however the $line variable does not print.

<$path_to_dir tries to read from that as if it's a filename -- not as if it's a list of lines. Technically it's valid for a filename to have newlines in it, strangley enough! The only invalid characters for a filename are NULLs and forward slashes.

Depending on what shell you're using you could do:

while read line1
do
done <<<"${list_of_lines}"

Also, you should always, always quote your variables unless you want them to start splitting when they end up with spaces in them. No reason not to.

That doesn't work. Now instead of printing the LINE --- 3 times , it prints LINE --- just once.

Also, I am not very clear what you meant by it trying to read line from filename.

I have a surrounding while loop to that above code and that works perfectly file

while read remotehost
do
 Above mentioned Code
done < "$remotehostlist"

This while loop works fine and provides me the value of remote host.
However the inner while loop does not print the value of $line.

That is the weird part

---------- Post updated at 02:41 PM ---------- Previous update was at 02:27 PM ----------

I changed the code to try this as well.. It still doesnt work!!

while read  remotehost
do
  ssh -t $2@$remotehost  <<REMOTE

   ls /path/to/dir | while read line
     do
        echo "LINE --- $line"
     done

REMOTE
done < "$remotehostlist"


This code still prints LINE --- 3 times. But does not print value of $line

Suddenly it's staring me in the face.

Even in a here-document, $line gets evaluated before the program is run, while it's still blank, so it becomes "LINE ---" before it even gets transmitted over ssh. Try escaping it like \$line.

1 Like

Thank you very much! That worked :slight_smile: