使用 ssh 读取一行后 while 循环退出
While loop exits after reading one line using ssh
您好,我有与以下条目绑定的文件名:
testnode1 eth0
tetnode2 eth2
现在我正在写一个 bash 脚本做一个循环,使用 while 将该条目放入变量然后将它用于下面的命令:
ssh $serv ifconfig | grep $nic
问题是它在第一次读取“testnode1”后提前退出,它不执行下一行“testnod2”
完整代码如下:
#!/bin/bash
cat bonding | while read line
do
serv=$(echo $line | awk '{print }')
nic=$(echo $line | awk '{print }')
echo $serv
ssh $serv ifconfig | grep $nic
done
输出:
testnode1
eth0 Link encap:Ethernet HWaddr 00:0C:29:99:C0:CD
预期输出
testnode1
eth0 Link encap:Ethernet HWaddr 00:0C:29:99:C0:CD
testnode2
eth2 Link encap:Ethernet HWaddr 00:0A:30:40:QB:A1
谁能指出我的错误,谢谢
那是因为 ssh
从标准输入读取。由于您正在循环读取文件,因此 ssh
会读取所有内容,并且在下一次迭代中,没有更多内容可读。因此,循环在一次迭代后退出。
你可以这样做:
ssh "$serv ifconfig | grep $nic" </dev/null
或
ssh -n $serv ifconfig | grep $nic
来自 ssh
手册:
-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.)
您好,我有与以下条目绑定的文件名:
testnode1 eth0
tetnode2 eth2
现在我正在写一个 bash 脚本做一个循环,使用 while 将该条目放入变量然后将它用于下面的命令:
ssh $serv ifconfig | grep $nic
问题是它在第一次读取“testnode1”后提前退出,它不执行下一行“testnod2”
完整代码如下:
#!/bin/bash
cat bonding | while read line
do
serv=$(echo $line | awk '{print }')
nic=$(echo $line | awk '{print }')
echo $serv
ssh $serv ifconfig | grep $nic
done
输出:
testnode1
eth0 Link encap:Ethernet HWaddr 00:0C:29:99:C0:CD
预期输出
testnode1
eth0 Link encap:Ethernet HWaddr 00:0C:29:99:C0:CD
testnode2
eth2 Link encap:Ethernet HWaddr 00:0A:30:40:QB:A1
谁能指出我的错误,谢谢
那是因为 ssh
从标准输入读取。由于您正在循环读取文件,因此 ssh
会读取所有内容,并且在下一次迭代中,没有更多内容可读。因此,循环在一次迭代后退出。
你可以这样做:
ssh "$serv ifconfig | grep $nic" </dev/null
或
ssh -n $serv ifconfig | grep $nic
来自 ssh
手册:
-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.)