Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

bash: nested interactive read within a loop that's also using read

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"

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You've correctly identified that the cause is that within the

while ...; do ...; done <<< "$shows"

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

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

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"

to clone the original FD 0 to FD 3 before replacing FD 0 with your string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...