1

Hi I have file name bonding with below entry:

testnode1 eth0
tetnode2  eth2

Now I'm writing a bash script do a loop using while to put that entry in to variable then use it to below command:

ssh $serv ifconfig | grep $nic

Problem is its exited to early after the first read " testnode1 " it does not execute the next line " testnod2"

Here is the whole code:

#!/bin/bash
cat bonding | while read line
do
    serv=$(echo $line | awk '{print $1}')
    nic=$(echo $line | awk '{print $2}')
    echo $serv
    ssh $serv ifconfig | grep $nic
done

output:

testnode1
eth0      Link encap:Ethernet  HWaddr 00:0C:29:99:C0:CD 

expected output

testnode1
eth0      Link encap:Ethernet  HWaddr 00:0C:29:99:C0:CD  
testnode2
eth2      Link encap:Ethernet  HWaddr 00:0A:30:40:QB:A1  

Can someone point me to my mistake, thanks

P.P
  • 117,907
  • 20
  • 175
  • 238
turffy
  • 33
  • 4

1 Answers1

2

That's because ssh reads from stdin. Since you are looping to read from a file, ssh reads everything and in the next iteration, there's nothing more to read. Hence, the loop exits after one iteration.

You can do:

ssh "$serv ifconfig | grep $nic" </dev/null

or

ssh -n $serv ifconfig | grep $nic

From the ssh manual:

 -n   

Redirects stdin from /dev/null (actually, prevents reading from stdin). This must be used when ssh is run in the background. A common trick is to use this to run X11 programs on a remote machine. For example, ssh -n shadows.cs.hut.fi emacs & will start an emacs on shadows.cs.hut.fi, and the X11 connection will be automatically forwarded over an encrypted channel. The ssh program will be put in the background. (This does not work if ssh needs to ask for a password or passphrase; see also the -f option.)

P.P
  • 117,907
  • 20
  • 175
  • 238