silence_of_the_lambdas
silence_of_the_lambdas

Reputation: 1282

Bash: while, read and more together

When using a combination of the while, read and more commands in a bash script, I received some output that should not be printed.

The minimal example consists of a shell script 'problem.sh' and two test files 'test.dat' and 'test2.dat':

problem.sh:

while read row; do
  #echo $row
  more test2.dat
  echo HERE
done < test.dat

test.dat:

test1
test2
test3

test2.dat

lefttop
abc
leftbot

The program is supposed to print three times the three rows of test2.dat in the terminal (number of while loop runs checked with echo HERE), however it gives out also test2 and test3 of test.dat at the beginning of the program execution (even if echo $row is commented out as above, else it additionally prints test1 at the beginning) and only runs once through the loop. Any help?

Upvotes: 0

Views: 181

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295403

Move test.dat away from stdin to FD 3, letting more use stdin uninterrupted:

while read -r row <&3; do
  #echo $row
  more test2.dat
  echo HERE
done 3< test.dat

That's assuming, of course that you want more to be able to interact with the user. If you just want to concatenate files together, use cat instead.

Upvotes: 3

Cyrus
Cyrus

Reputation: 88591

Replace more test2.dat by more test2.dat < /dev/null to stop more reading from stdin (test.dat), too.

Upvotes: 1

Related Questions