Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...