如何停止并强制用户在bash脚本中输入特定值?

时间:2016-06-28 13:25:29

标签: bash

我正在尝试强制用户在bash脚本中输入特定值,但它没有提示,有人可以建议吗?

while IFS= read -r line;
do
until [ "$CONTINUE_EXECUTION" = "Y" -o "$CONTINUE_EXECUTION" = "N" ]; do
  echo "Please press Y to continue or N to exit"
  read CONTINUE_EXECUTION
done
echo $line
done < xx2.txt

1 个答案:

答案 0 :(得分:3)

脚本中的问题是read -r lineread CONTINUE_EXECUTION从xx2.txt文件读取。 stdin现已映射到xx2.txtread都从那里获取输入。

一种方法是使用exec创建新的fd并使用read -u从该fd中读取。

exec 5<xx2.txt
while read -u 5 line   # read from xx2.txt
do
until [ "$CONTINUE_EXECUTION" = "Y" -o "$CONTINUE_EXECUTION" = "N" ]; do
  read -p "Please press Y to continue or N to exit: " CONTINUE_EXECUTION  
       # read from stdin, which is the user's terminal at this point
done
echo $line
CONTINUE_EXECUTION=""
done

PS:我删除了代码的一些部分,例如IFS,因为我想解释所需更改的主要部分。