Page 1 of 1

Bash: "read" input while inside a while/read loop

Posted: Mon Oct 12, 2015 2:54 pm
by peter_b
[PROBLEM]
Usually, in bash the command "read" is used for "press any key to continue" scenarios:

Code: Select all

read -p "press any key..."
This conflicts however, when calling it inside a while loop that uses "read" to e.g. iterate through a file:

Code: Select all

while read LINE; do
   ...
   read -p "press any key"
done < $FILE
The "read" used to wait for a key, literally "eats up" every 2nd line of the input file, because the stdin is now colliding between 2 different inputs.
:?

[SOLUTION]
Use a for loop with "cat" instead of while/read:

Code: Select all

for LINE in $(cat $FILE); do
  ...
  read -p "press any key"
done
:D

NOTE: Versions that use a different pipe than stdin can be found in the site, linked below.

Links: