您好,我的文件名与以下条目绑定(bind):
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 $1}')
nic=$(echo $line | awk '{print $2}')
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.)
关于bash - 使用 ssh 读取一行后 while 循环退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34103425/