bash 当文件已重定向到 stdin 时,读取用户输入的 stdin
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8886683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read stdin for user input when a file is already redirected to stdin
提问by Aram Papazian
So I'm trying to do something like the following:
所以我正在尝试执行以下操作:
while read line; do
read userInput
echo "$line $userInput"
done < file.txt
So say file.txt has:
所以说 file.txt 有:
Hello?
Goodbye!
Running the program would create:
运行该程序将创建:
Hello?
James
Hello? James
Goodbye!
Farewell
Goodbye! Farewell
The issue (naturally) becomes that the userinput read reads from stdin which in our case is file.txt. Is there a way to change where it's reading from temporarily to the terminal in order to grab user input?
问题(自然)变成了用户输入读取从 stdin 读取,在我们的例子中是 file.txt。有没有办法将它从临时读取的位置更改为终端以获取用户输入?
Note: The file I am working with is 200,000 lines long. and each line is about 500 chars long. So keep that in mind if needed
注意:我正在处理的文件有 200,000 行。每行大约 500 个字符长。所以如果需要,请记住这一点
回答by jcollado
Instead of using redirection, you can open file.txtto a file descriptor (for example 3) and use read -u 3to read from the file instead of from stdin:
您可以打开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
Alternatively, as suggested by Jaypal Singh, this can be written as:
或者,按照 Jaypal Singh 的建议,这可以写为:
while read line <&3; do
echo $line
read userInput
echo "$line $userInput"
done 3<file.txt
The advantage of this version is that it also works in sh(the -uoption for readdoesn't work in sh).
此版本的优点是它也适用于sh(的-u选项在read中不起作用sh)。

