Bash - How to do a "read -p" inside a while loop?

Hi there guys!

I was trying to do:

while read line; do
if [ $cont -eq 5 ]; then
   read -p "Press Enter to continue..."
   cont=0
fi

echo $line

let cont++

done < file.txt

However, I have read that the read -p would not work in a while loop...

I was wondering if there is any other way to pause the loop to wait for a key to continue..

I have tried putting the 'read -p "text"' in a function and calling it inside the while loop, also doing 'dd count=1 1>/dev/null 2>&1'... But I've had no luck..

Any help would be greatly appreciated!

Thanks!

Regards,
Rplae.

The standard input to your loop is redirected from file.txt , so both read commands in the loop are reading from that file.

If you want to have the outer read read from the file and the inner read read from the script's standard input, you can try something like:

#!/bin/bash
cont=0
while read line <&3
do	if [ $cont -eq 5 ]
	then	read -p "Press Enter to continue..."
		cont=0
	fi
	printf '%s\n' "$line"
	cont=$((cont + 1))
done 3< file.txt

or, if you want the inner read to read from the process's controlling terminal, you can try something more like:

#!/bin/bash
cont=0
while read line
do	if [ $cont -eq 5 ]
	then	read -p "Press Enter to continue..." < /dev/tty
		cont=0
	fi
	printf '%s\n' "$line"
	cont=$((cont + 1))
done < file.txt
1 Like

Wow! Thank you for your reply! I will try that as soon as I get home tonight :slight_smile:

---------- Post updated at 07:25 PM ---------- Previous update was at 02:48 PM ----------

Don Cragun!

I thank you very much for your help both solutions worked like a charm

Thanks again!
Rplae