码迷,mamicode.com
首页 > 系统相关 > 详细

shell中使用while循环ssh时只循环第一行的问题解决

时间:2015-07-25 20:07:38      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:shell while循环每一行

    最近在写一个shell脚本,本想使用for循环来读取文件里面的内容,可是发现文件里每一行都有空格的,明显用for循环行不通过,我的目的是想一行一行读取文件内容,于是果断使用while循环来实现,可问题来了,当ssh完第一行后就退出了,后面都没有执行成功,如何避免自动读取一行就跳出while循环,此文将详细解释其原因。

文件内容如下:
[root@Linus_hai~]#cat 2.txt
scjz 2144 10.16.100.113  89
scjz 2144 10.16.100.114  90

部分代码如下:
#!/bin/bash
ServerDir=/data/scjz_server
IpList=$1
Port=22
Num=3300
echo -e "\e[32m`cat $IpList` \e[0m"
echo -e "\033[31m 是否操作以上服务器的游戏服务,请确认(yes or no): \033[0m"
read confirm
if [ "$confirm" == "yes" ];then
while read line
do
   Platform=`echo $line |awk ‘{print $2}‘`
   Ip=`echo $line |awk ‘{print $3}‘`
   Id=`echo $line |awk ‘{print $4}‘`
   Server=`ssh -p $Port $Ip "cd $ServerDir;/bin/ls -d *_${Platform}_s${Id}"`
   index=`echo $Server |awk -F_ ‘{print $1}‘`
   MysqlPort=$(expr $index + $Num)
   echo $Ip $Server
done < $1
fi

    经过一番试验以后发现,是while中使用重定向机制,2.txt文件中的信息都已经读入并重定向给了整个while语句,所以当我们在while循环中再一次调用read语句,就会读取到下一条记录。问题就出在这里,ssh语句正好回读取输入中的所有东西,这就导致调用完ssh语句后,输入缓存中已经都被读完了,当read语句再读的时候当然也就读不到纪录,循环也就退出了。

改进方法是,修改ssh那一行,在ssh后面加上重定向输入就行了:

正确代码如下:
#!/bin/bash
ServerDir=/data/scjz_server
IpList=$1
Port=22
Num=3300
echo -e "\e[32m`cat $IpList` \e[0m"
echo -e "\033[31m 是否操作以上服务器的游戏服务,请确认(yes or no): \033[0m"
read confirm
if [ "$confirm" == "yes" ];then
while read line
do
   Platform=`echo $line |awk ‘{print $2}‘`
   Ip=`echo $line |awk ‘{print $3}‘`
   Id=`echo $line |awk ‘{print $4}‘`
   Server=`ssh -p $Port $Ip "cd $ServerDir;/bin/ls -d *_${Platform}_s${Id}" < /dev/null`
   index=`echo $Server |awk -F_ ‘{print $1}‘`
   MysqlPort=$(expr $index + $Num)
   echo $Ip $Server
done < $1
fi

这样,在while语句中也能顺利的执行ssh语句了。

本文出自 “菜鸟中的战斗机” 博客,请务必保留此出处http://linushai.blog.51cto.com/4976486/1678317

shell中使用while循环ssh时只循环第一行的问题解决

标签:shell while循环每一行

原文地址:http://linushai.blog.51cto.com/4976486/1678317

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!