[Solved] Endless while loop when compare files

Hi All,

I've written a script to read 2 files and compare the contents using while loop but somehow when $line is not found in test2, the script will continue looping.
Below is my code, pls advise what could went wrong

TIA
Nick

for line in test1.txt | while read line
do
   grep -i $line test2.txt >/dev/null
   exitcode=$?
   if [ $exitcode = 0 ]; then
      echo "$line : String Exists"
   else
      echo "String does not exists"
   fi

missing the done or is it a bad copy paste?

Why do you not use:

while read line
do
   grep -i $line test2.txt >/dev/null
   exitcode=$?
   if [ $exitcode = 0 ]; then
      echo "$line : String Exists"
   else
      echo "String does not exists"
   fi
done < test1.txt
while read line
do
   grep -i $line test2.txt >/dev/null
   exitcode=$?
   if [ $exitcode -eq 0 ]; then
      echo "$line : String Exists"
   else
      echo "String does not exists"
   fi
done < test1.txt

--ahamed

---------- Post updated at 09:31 AM ---------- Previous update was at 09:31 AM ----------

oops... :wink:
vbe already posted!

--ahamed

Hi,

tried to amend the code but loop still endless :

while read line 
        do 
        grep "$line" test2.txt >> /dev/null 

        if [ $? = 1 ]; then 
                /usr/bin/echo "No Error found" 
               else 
               /usr/bin/echo "Error found" 
              exit 2 
        fi 
done < test1.txt

---------- Post updated at 11:51 AM ---------- Previous update was at 11:40 AM ----------

Hi,

Problem fixed. It was due to other parts of the script that caused the loop to be endless.

Thanks for the help.

Nick