如何暂停"读取线"

时间:2017-09-03 07:46:36

标签: bash

我知道 (1)我可以用

循环遍历文件的行
while read line  
do  
    something  
done < file 

(2)我可以用

暂停我的程序
something  
read -p "press any key to continue..."  ## pause here waiting for key in  
something 

然而,暂停技巧在这样的读取循环中不起作用

while read line  
do  
    something  
    read -p "press any key to continue..."  ## suppose to pause here  
done < file 

那么为什么会这样,以及如何克服它?

2 个答案:

答案 0 :(得分:3)

您的读取命令也从stdin(从您的文件中)读取。

使用Linux,您可以使用:

read -p "press any key to continue..." < /dev/tty

答案 1 :(得分:0)

exec 3< words
while read -u 3 word; do
    printf 'Got "%s"\n' "$word"
    read -p 'Press enter.'
done

首先打开文件描述符3(通常由shell使用),然后将文件words的内容发送给它。

然后read从此文件描述符(-u 3)读取,循环显示结果并等待用户在标准输入上的输入。

循环不起作用的原因是您从文件中重定向两个 read调用的输入。从循环中的标准输入读取的任何内容都将从文件中获取数据。

相关问题