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

前端之家收集整理的这篇文章主要介绍了bash – 当文件已被重定向到stdin 时,读取用户输入的stdin前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > Read input in bash inside a while loop5个
所以我试图做如下的事情:
  1. while read line; do
  2. read userInput
  3. echo "$line $userInput"
  4. done < file.txt

所以说file.txt有:

  1. Hello?
  2. Goodbye!

运行程序将创建:

  1. Hello?
  2. James
  3. Hello? James
  4. Goodbye!
  5. Farewell
  6. Goodbye! Farewell

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

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

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

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

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

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

猜你在找的Bash相关文章