bash – 当文件已被重定向到stdin 时,读取用户输入的stdin

参见英文答案 > Read input in bash inside a while loop5个
所以我试图做如下的事情:
while read line; do
    read userInput
    echo "$line $userInput"
done < file.txt

所以说file.txt有:

Hello?
Goodbye!

运行程序将创建:

Hello?
James
Hello? James
Goodbye!
farewell
Goodbye! farewell

这个问题(当然)就是用户输入读取从stdin读取,在我们的例子中是file.txt.有没有办法改变从临时读取到终端的位置,以便抓住用户输入?

注意:我正在使用的文件是20万行长.每行约500字符长.所以请记住,如果需要的话

而不是使用重定向,您可以打开file.txt到文件描述符(例如3),并使用read -u 3从文件而不是从stdin读取:
exec 3<file.txt
while read -u 3 line; do
    echo $line
    read userInput
    echo "$line $userInput"
done

或者,如Jaypal Singh所建议的,这可以写成:

while read line <&3; do
    echo $line
    read userInput
    echo "$line $userInput"
done 3<file.txt

这个版本的优点是它也可以在sh中使用(读取的-u选项在sh中不起作用).

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...