bash 是否支持在读取循环中嵌套读取?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16308110/
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
Does bash support doing a read nested within a read loop?
提问by ddoxey
The bash read command is very convenient for:
bash 读取命令非常方便:
- read-p to prompt the user and capture input from the user
- while readloop to iterate through the lines of a file.
- read-p 提示用户并捕获用户的输入
- while read循环遍历文件的行。
However, I'm having issues attempting to do both simultaneously.
但是,我在尝试同时执行这两项操作时遇到了问题。
For example:
例如:
#!/bin/bash
while read item
do
echo Item: $item
read -p "choose wisely: " choice
echo You still have made a $choice.
done < /tmp/item.list
Rather than blocking and standing by for the user to enter a choice, bash is populating $choice with the next item in the item.list file.
bash 不是阻止和等待用户输入选择,而是用 item.list 文件中的下一个项目填充 $choice。
Does bash support doing a read nested within a read loop?
bash 是否支持在读取循环中嵌套读取?
回答by Steven Penny
The simplest fix is to have the outer readread from a different file
descriptor instead of standard input. In Bash, the -uoption make that a
little easier.
最简单的解决方法是read从不同的文件描述符而不是标准输入读取外部。在 Bash 中,该-u选项使这更容易一些。
while read -u 3 item
do
# other stuff
read -p "choose wisely: " choice
# other stuff
done 3< /tmp/item.list

