一、简介
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
doecho $info
read -p "input(y/n):" ISGOON
if [ "$ISGOON" == "y" ];then
continue
else
exit
fi
done
测试脚本的目的:读取test.txt文件中的内容,如果想继续输出,则输入y;否则,输入n。
测试截图:

通过调试脚本,可以发现,在执行read -p 的时候,read命令读取到的值,是‘2’
三、解决办法
1、在使用read的时候,加上/dev/tty。如下:
cat test.sh
cat test.txt|while read info
doecho $info
read -p "input(y/n):" ISGOON if [ "$ISGOON" == "y" ];then
continue
else
exit
fi
done
测试截图:

可以看到,这次可以根据read读取到的值,进行相应的流程控制。