Open vieyahn2017 opened 4 years ago
比如这样的测试脚本
sleep 10
echo "read eee"
read -s eee
echo "===${ee
在sleep 10阶段,在键盘上随便按键,其输入内容会被缓冲区记录,
后续执行read的时候,读入的变量跟预期的不符,是之前按键输入的。
这就是缓冲区没清空导致的
输入脚本如何刷新输入缓冲区 https://segmentfault.com/q/1010000000260137
#!/bin/bash
#刷新标准输入的函数
function flush() {
local RET=0
while [ $RET -eq 0 ]
do
read -t 1
RET=$?
done
}
function menu() {
flush
echo "please input your choice:(a or o)?"
read input
case $input in
a|o)
echo "your choice is " $input
;;
*)
echo "invalid input! please input again!"
menu
;;
esac
}
echo "sleep 10s ..."
sleep 10 #这段睡眠时间里如果有输入,也不会被下面的menu函数接收到,因为flush函数会把它们先读走
menu
我改造的:
##刷新标准输入的缓冲区
function flush_before_read() {
local RET=0
while [ $RET -eq 0 ]
do
read -t 1
RET=$?
done
}
func_read_yes_no () {
flush_before_read
retry_times=1
while [ $retry_times -le 3 ]; do
read yesno
if [[ "$yesno" == "yes" ]] || [[ "$yesno" == "y" ]];then
echo $1
return
elif [[ "$yesno" == "no" ]] || [[ "$yesno" == "n" ]];then
echo "you choose no, now will exit install."
exit 0
else
echo "Invalid input, (yes/no) expected. Please re-enter."
retry_times=`expr $retry_times + 1`
fi
done
echo "Invalid input for more than 3 times, exit now."
exit 1
}
刷新标准输入的缓冲区