0

When I am writing a shell script, I have a problem about nested read as the following codes.

while read entry
do
    IFS=' ' read -a array <<< "$entry"

    read -p "Read from keyboard" keyin

    case $keyin in
       [a]* ) .....
       .....
    esac
done << file

I expected to read keyboard input but the 'read -p .... keyin' always read value from 'file'. Is anyone have idea about this? Any alternative method for me to read keyboard input in this situation?

Thanks.

1
  • Is the shell bash? If so, say so (otherwise you might be asking about Korn shell or zsh or Dash instead, or as well). Add the tag and say so in the question. Commented May 29, 2014 at 6:30

1 Answer 1

3

Assuming you're using bash, you can arrange to read from different file descriptors:

while read -r -u 3 entry
do
    IFS=' ' read -a array <<< "$entry"

    read -p "Read from keyboard" keyin

    case $keyin in
       [a]* ) .....
       .....
    esac
done 3< file

The 3< redirects file as input to file descriptor 3; the -u 3 tells read to read from file descriptor 3. Thus, the outer loop is acting on lines from the file, leaving the inner read to act on keyboard input. The -r is modern but necessary to avoid unexpected behaviour (I learned to program without it; I resent needing to use it — the flag should be necessary to enable the modified behaviour).

Note that the original code in the question used << file; that starts a here document, but clearly wasn't what was intended since no body or end of the here document was shown.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.