bash:循环中的嵌套交互式读取,该循环也使用读取 [英] bash: nested interactive read within a loop that's also using read

查看:17
本文介绍了bash:循环中的嵌套交互式读取,该循环也使用读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在这个 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 read循环中使用生成的面向行的数据

So a file is read, "processed" then the resulting line oriented data is used in a while read loop

但是 while 循环中的 read 行没有按预期工作,即它不等待用户响应,大概是由于它封装了 while read 上下文.

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"

loop, stdin 已被重定向,因此 read 不再从键盘读取.

loop, stdin has been redirected, thus read is no longer reading from the keyboard.

您可以通过使用非 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,允许正常的 read(没有 -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.

这篇关于bash:循环中的嵌套交互式读取,该循环也使用读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆