bash - 使用 ssh 读取一行后 while 循环退出

标签 bash shell scripting

您好,我的文件名与以下条目绑定(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/

相关文章:

bash - 如何使文本在 shell 脚本中闪烁

python - 如何找到未列出或丢失的号码?

java - 重定向 shell 脚本中的输出

javascript - 组合多个 jQuery 脚本

linux - shell脚本可以在运行一些步骤后让自己在后台运行吗?

bash - 如何递归搜索和删除目录中所有文件中的^M?

linux - 我是否可以正确设置此脚本以根据用户输入运行特定命令?

regex - Ant 正则表达式(regexp 元素)模式中的转义字符是什么

PowerShell - 如何计算参数数量

linux - 如何在 vi 编辑器中显示登录服务器的用户的输出?