Execute command on remote host via ssh

How should i make the following code working

#!/bin/bash
INPUTFILE="test.txt"
while read STRING; do
IP=`host -t A $STRING | awk '{print $NF}'`
HOSTNAME=`ssh -oPasswordAuthentication=no -oStrictHostKeyChecking=no $IP "hostname"`
echo $HOSTNAME > out.txt
done < $INPUTFILE

At this moment while loop is not working - script finishes after first pass. The problem is with the following line

HOSTNAME=`ssh -oPasswordAuthentication=no -oStrictHostKeyChecking=no $IP "hostname"`

when i comment it out the loops works. How could one fix it?

HOSTNAME=`ssh -oPasswordAuthentication=no -oStrictHostKeyChecking=no $IP "hostname"`

This executes the command (attempts to connect) and saves its output in the variable HOSTNAME .
Further, for each loop you overwrite out.txt with the last loop its output.

And to help you further, what do you want to achieve?

ssh will read stdin and thus test.txt until EOF and empty the input to the read command. Use the -n option to ssh .

using ssh with "-f" arg solved my issue.