一、简介
echo $info
read -p "input(y/n):" ISGOON
if [ "$ISGOON" == "y" ];then
continue
else
exit
fi
done
echo $info
read -p "input(y/n):" ISGOON if [ "$ISGOON" == "y" ];then
continue
else
exit
fi
done
在shell编程中,有时候为了实现对逻辑流程的控制,会在while循环中再次使用read命令。可是,在这种情况下,循环中的read命令是失效的。这是为什么?有什么解决办法呢?
二、现象
测试脚本:
cat test.txt
1
2
3
4
5
cat test.sh
cat test.txt|while read info
do
echo $info
read -p "input(y/n):" ISGOON
if [ "$ISGOON" == "y" ];then
continue
else
exit
fi
done
测试脚本的目的:读取test.txt文件中的内容,如果想继续输出,则输入y;否则,输入n。
测试截图:
![](http://img.blog.itpub.net/blog/attachment/201501/6/26418713_1420548619YD1S.png?x-oss-process=style/bb)
通过调试脚本,可以发现,在执行read -p 的时候,read命令读取到的值,是‘2’
三、解决办法
1、在使用read的时候,加上/dev/tty。如下:
cat test.sh
cat test.txt|while read info
do
echo $info
read -p "input(y/n):" ISGOON if [ "$ISGOON" == "y" ];then
continue
else
exit
fi
done
测试截图:
![](http://img.blog.itpub.net/blog/attachment/201501/6/26418713_1420548628DpOg.png?x-oss-process=style/bb)
可以看到,这次可以根据read读取到的值,进行相应的流程控制。
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/26418713/viewspace-1392523/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/26418713/viewspace-1392523/