问题描述
一个人怎么code在这个while循环交互响应?
How does one code an interactive response in this while loop?
#!/bin/bash
shows=$(< ${HOME}/.get_iplayer/tv.cache)
# ...
# ... stuff with shows omitted ...
# ...
function print_show {
# ...
return
}
while read -r line
do
print_show "$line"
read -n 1 -p "do stuff? [y/n] : " resp # PROBLEM
# ...
# resp actions omitted
# ...
done <<< "$shows"
因此,一个文件被读取,处理,那么所产生的面向行的数据是在而读
循环中使用
但while循环中读取行不工作打算,那就是它不会等待用户的响应,presumably由于而读
方面,它是由封装。
But the read line within the while loop doesn't work as intended, that is it doesn't wait for the user response, presumably due to the while read
context it is encapsulated by.
能否请你建议如何解决这一问题或备用机制?
Could you please suggest how to fix this or an alternate mechanism?
推荐答案
您已经正确识别的原因是在
You've correctly identified that the cause is that within the
while ...; do ...; done <<< "$shows"
循环,标准输入被重定向,从而读
不再从键盘读取。
您可以通过使用0以外的文件描述符解决这个问题;例如,
You can solve this by using a file descriptor other than 0; for example,
while read -r -u 3 line; do ...; done 3<${HOME}/.get_iplayer/tv.cache
将使用FD 3的文件,而不是FD 0,允许正常读
(不包括 -u
)使用原装标准输入,或
will use FD 3 for the file rather than FD 0, allowing the normal read
(without -u
) to use original stdin, or
while ...; do read -n 1 -p "do stuff? [y/n] : " -u 3 resp; done 3<&0 <<< "$shows"
与您的字符串替换FD 0之前,原来的FD 0克隆到FD 3。
to clone the original FD 0 to FD 3 before replacing FD 0 with your string.
这篇关于庆典:这是使用读也是一个循环内嵌套的互动阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!