参见英文答案 >
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中不起作用).