I have a bash script with a construction like this:

while read foo bar baz;
    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?

2 Answers 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

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .