Read stdin for user input when a file is already redirected to stdin [duplicate]

Instead of using redirection, you can open file.txt to a file descriptor (for example 3) and use read -u 3 to read from the file instead of from stdin:

exec 3<file.txt
while read -u 3 line; do
    echo $line
    read userInput
    echo "$line $userInput"
done

Alternatively, as suggested by Jaypal Singh, this can be written as:

while read line <&3; do
    echo $line
    read userInput
    echo "$line $userInput"
done 3<file.txt

The advantage of this version is that it’s POSIX compliant (the -u option for read does not appear in POSIX shells such as /bin/sh).

Leave a Comment