转自:https://zhidao.baidu.com/question/432126157616850964.html html
问题:缓存
我如今是想用一个脚本获取必定列表服务器的运行时间。首先我创建一个名字为ip.txt的IP列表(一个IP一行),再建好密钥实现不用密码直接登陆。而后写脚本以下:
#!/bin/bash
while read ips;
do
echo $ips;
done < ip.txt
脚本实现了逐行读取列表中的IP,可是:
#!/bin/bash
while read ips;
do
echo $ips;
upt=`ssh root@$ips "uptime"`;
echo $upt;
done < ip.txt
脚本实现了一个IP的检测,就直接跳出来了。大神,求救!!!bash
大神解答:服务器
一、while使用机制,ip.txt文件中的信息都已经读入并给了整个while语句。因此当咱们在while循环中再一次调用read语句,就会读取到下一条记录。问题就出在这里,ssh语句正好回读取输入中的全部东西。为了禁止ssh读全部东西增长一个< //null,将ssh 的输入输入 while read ips; do echo $ips; upt=`ssh root@${ip1} uptime < //null;`; echo $upt; done < ip.txt; 二、用for for ips in `cat ip.txt`; do echo ${ips}; upt=`ssh root@${ips} uptime`; echo $upt; done
高手啊,讲解得很是透彻很是专业。我还想问你个问题: 一、为何用</dev/null重定向就能够禁止ssh读取全部东西呢?/dev/null是否是把远程的值重置为空呢?这个问题有点抽象。 二、兄弟提到for语句,也写得很精辟。for语句怎么不存在while语句刚才的那个问题? 三、刚才楼上有个兄弟提到用-n参数,我试过也是能够的,你能够帮他回答一下为何这个-n也能够的吗?
追答ssh
一、< /dev/null是告诉ssh若是要获取就从/dev/null获取,避免了获取while缓存 二、for没有一次把文件内容缓存获取过来 三、看一下man ssh -n参数 Redirects stdin from /dev/null (actually, prevents reading from stdin).和</dev/null道理同样。