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

Linux howto's, compile information, information on whatever we learned on working with linux, MACOs and - of course - Products of the big evil....
Post Reply
User avatar
peter_b
Chatterbox
Posts: 383
Joined: Tue Nov 12, 2013 2:05 am

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

Post 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:
Post Reply