Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use `while read -r line` while also checking if another file is not empty in BASH?

I have a while loop, simplified like this:

while read -r line
do
    (delete some lines from file2.txt)
done < file.txt

If file2.txt is empty, then this while loop has no need to function any longer.

In other words, I need this:

while read -r line AND file2.txt IS NOT EMPTY
do
    (delete some lines from file2.txt
done < file.txt

I've tried to combined while read -r line with -s file2.txt, but the result does not work:

while [ read -r line ] || [ -s file2.txt ]
do
    (delete some lines from file2.txt)
done < file.txt

How can I use this while loop to read the lines in a file while also checking that another file is not empty?

like image 625
Village Avatar asked Nov 30 '22 19:11

Village


1 Answers

Combine the read and the test as:

while read -r line && [ -s file2.txt ]
do
  # (delete some lines from file2.txt)
  echo "$line"
done <file.txt

This will check, before every iteration of the loop, whether file2.txt is non-empty.

like image 136
Joe Avatar answered Dec 04 '22 04:12

Joe