Search code examples
linuxbashloopsif-statementredhat

loop through a directory and check if it exist in another directory


I have a folder with 20000 files in directory A and another folder with 15000 file in another directory B i can loop through a directory using:

DIR='/home/oracle/test/forms1/'

for FILE in "$DIR"*.mp
do
   filedate=$( ls -l --time-style=+"date %d-%m-%Y_%H-%M" *.fmx |awk  '{print $8 $7}')
    echo "file New Name $FILE$filedate "
#    echo "file New Name $FILE is copied "
done

I need to loop through all the files in directory A and check if they exist in directory B

I tried the following but it doesn't seem to work:

testdir='/home/oracle/ideatest/test/'
livedir='/home/oracle/ideatest/live/'

for FILET in "$testdir" #
do
    testfile=$(ls $FILET)
    echo $testfile

    for FILEL in "$livedir"
    do
        livefile=$(ls $FILEL)

        if [ "$testfile" = "$livefile" ]
        then
            echo "$testfile"
            echo "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy"
        else
            echo "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn"
        fi
    done
done

i'am trying to fix the result of years of bad version control we have that very oly script that send a form to live enviorment but every time it's compiled and sent the live version is named like (testform.fmx) but in test dir there is like 10 files named like (testform.fmx01-12-2018) (testform.fmx12-12-2017)(testform.fmx04-05-2016) as a reuslt we lost track of the last source sent to live enviroment that's why i created this

filedate=$( ls -l --time-style=+"date %d-%m-%Y_%H-%M" *.fmx |awk 
'{print $8 $7}')
echo "file New Name $FILE$filedate " 

to match the format and loop through each dir and using ls i can find the last version by matching the size and the year and month


Solution

  • You can basicly use diff command to compare the files and directories. diff folderA folderB I think you do not really need to use a loop for that..

    If really you want to use a loop around, you may want to compare the files as well.

    #!/bin/bash
    DIR1="/home/A"
    DIR2="/home/B"
    CmpCmn=/usr/bin/cmp
    DiffCmn=/usr/bin/diff
    
    for file1 in $DIR1/*; do #Get the files under DIR1 one by one
            filex=$(basename $file1) #Get only the name ofthe ile
            echo "searching for $filex"
             $DiffCmn $filex $DIR2  #Check whether the file is under DIR2 or not
            if [ $? -ne 0 ]
            then
                    echo " No file with $filex name under $DIR2 folder"
            else
                    echo " $filex exists under $DIR2" 
                    $CmpCmn  $file1 $DIR2/$filex  #Compare if the files are exactly same
                    if [ $? -ne 0 ]
                    then
                             echo " $filex is not same"
                     else
                             echo " $filex is the same"
                     fi
    fi
            done