bash:嵌套的交互式读取在一个';它也使用read

bash:嵌套的交互式读取在一个';它也使用read,bash,while-loop,interactive,Bash,While Loop,Interactive,如何在这个while循环中编写交互式响应 #!/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] :

如何在这个while循环中编写交互式响应

#!/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"
#/bin/bash
shows=$(<${HOME}/.get\iplayer/tv.cache)
# ...
# ... 省略了节目的东西。。。
# ...
功能打印显示{
# ...
返回
}
而read-r行
做
打印并显示“$line”
阅读-n 1-p“做些什么?[y/n]:”回答问题
# ...
#省略响应动作
# ...

完成您已正确确定原因是

while ...; do ...; done <<< "$shows"
将对文件使用FD 3而不是FD 0,允许正常的
读取
(无
-u
)使用原始标准输入,或

while ...; do read -n 1 -p "do stuff? [y/n] : " -u 3 resp; done 3<&0 <<< "$shows"

while。。。;请阅读-n1-p“做些什么?[y/n]:”-u3 resp;完成3由于您已经将整个文件读入内存,请将其读入数组而不是单个字符串

# Requires bash 4 or later
mapfile -t loop_input < $HOME/.get_iplayer/tv.cache

for line in "${loop_input[@]}"; do
    print_show "$line"
    read -n 1 -p "do stuff? [y/n] : " resp
done
或者,您不能将文件全部读入内存:

while read -u 3 line; do
    ....
done 3< $HOME/.get_iplayer/tv.cache
读取时-u3行;做
....
完成3<$HOME/.get_iplayer/tv.cache

Neat,不过要注意在Bash 4中添加了
mapfile
。谢谢。我会把它加到我的工具箱里。
declare -a loop_input
while read; do loop_input+=("$REPLY"); done

for line in "${loop_input[@]}"; do
    ...
done
while read -u 3 line; do
    ....
done 3< $HOME/.get_iplayer/tv.cache