Wait for keyboard input inside a while-read loop

5,207

Solution 1

The following /bin/sh code opens file descriptor 3 as a copy of standard input. Inside the loop, the read keypress reads from this new file descriptor, and not from the file fed into the loop itself. At the end, the file descriptor is explicitly closed.

exec 3<&0
while read -r foo bar baz; do
    printf 'Processing %s, %s and %s\n' "$foo" "$bar" "$baz"
    printf 'Press <enter> to continue: ' >&2
    read keypress <&3
done <file
exec 3<&-

echo 'Done.'

This allows you to use, e.g.,

yes | ./script.sh

to "automatically press enter" at every prompt.

Solution 2

Feeding a file into the loop will affect each read instance in the loop unless explicitly specified otherwise. The following worked:

echo "Press [ENTER] to continue"
read -s < /dev/tty
Share:
5,207

Related videos on Youtube

user149408
Author by

user149408

Updated on September 18, 2022

Comments

  • user149408
    user149408 about 1 year

    I have a bash script with a construction like this:

    while read foo bar baz;
    do
        echo "Processing $foo $bar $baz"
        # more code here
    done < /etc/somefile
    

    Inside the loop, I would like the script to wait for keyboard input (basically just "press Enter to continue". However, the following code inside the loop

    echo "Press [ENTER] to continue"
    read -s
    

    doesn’t cause the script to stop there—apparently it takes its input from the supplied file rather than the keyboard. How can I force it to read from the keyboard?