加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 18:55:37 所属栏目:安全 来源:网络整理
导读:参见英文答案 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?JamesHello? JamesGoodbye!Farew
参见英文答案 > 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中不起作用).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读