Shell 脚本用于比较目录中的多个文件,但仅将不匹配的文件附加为电子邮件附件

Shell 脚本用于比较目录中的多个文件,但仅将不匹配的文件附加为电子邮件附件

我正在比较目录中的多个文件。这些文件中有些匹配,有些不匹配。我可以使用 diff 命令输出差异。我想将不匹配的文件作为附件通过电子邮件发送。

#!/bin/bash

DIR1=/usr/local/apps/B2B/filecompare/inf
DIR2=/usr/local/apps/B2B/filecompare/gen/genB

DEST_DIR1=/usr/local/apps/B2B/filecompare/moved/cmpinf
DEST_DIR2=/usr/local/apps/B2B/filecompare/moved/cmpgen

export RESULT=$1

for FILE1 in `ls $DIR1`
do
    if [ ! -f $DIR2/$FILE1 ]; then
        echo "  $FILE1 exists in $DIR1 but not found in $DIR2. Skipping file." >> $RESULT
    else
        echo "  Comparing $DIR1/$FILE1 $DIR2/$FILE1." >> $RESULT
        diff -B $DIR1/$FILE1 $DIR2/$FILE1 >> $RESULT
        #diff $DIR1/$FILE1 $DIR2/$FILE1 >>RESULT
        echo "  Done comparing $DIR1/$FILE1 $DIR2/$FILE1." >> $RESULT

        mv $DIR1/$FILE1 $DEST_DIR1
        mv $DIR2/$FILE1 $DEST_DIR2
        echo "  Done moving files" >> $RESULT

    fi
done

for FILE2 in `ls $DIR2`
do
    if [ ! -f $DIR1/$FILE2 ]; then
        echo "  $FILE2 exists in $DIR2 but not found in $DIR1. Skipping file." >> $RESULT
    fi
done

echo "  Done comparing." >> $RESULT
zip -r $DEST_DIR1/downlaod.zip $DEST_DIR1/$FILE1 $DEST_DIR2/$FILE1
mail -a $DEST_DIR1/downlaod.zip [email protected]

谢谢

答案1

这应该可行。它在第一个循环中构建不同文件的列表,然后使用不同的 zip 命令将它们压缩。

#!/bin/bash

DIR1=/usr/local/apps/B2B/filecompare/inf
DIR2=/usr/local/apps/B2B/filecompare/gen/genB

DEST_DIR1=/usr/local/apps/B2B/filecompare/moved/cmpinf
DEST_DIR2=/usr/local/apps/B2B/filecompare/moved/cmpgen

export RESULT=$1
touch different.txt

for FILE1 in `ls $DIR1`
do
    if [ ! -f $DIR2/$FILE1 ]; then
        echo "  $FILE1 exists in $DIR1 but not found in $DIR2. Skipping file." >> $RESULT
    else
        echo "  Comparing $DIR1/$FILE1 $DIR2/$FILE1." >> $RESULT
        diff -B $DIR1/$FILE1 $DIR2/$FILE1 >> $RESULT
        #diff $DIR1/$FILE1 $DIR2/$FILE1 >>RESULT
        echo "  Done comparing $DIR1/$FILE1 $DIR2/$FILE1." >> $RESULT

        # NEW: register if there is a diff
        is_diff=$(diff -q $DIR1/$FILE1 $DIR2/$FILE2 >/dev/null; echo $?)

        # NEW: build a list of the files that are different
        if [ "$is_diff" -gt 0 ]; then
            echo $DEST_DIR1/$FILE1 >> different.txt
            echo $DEST_DIR2/$FILE1 >>  different.txt
        fi


        mv $DIR1/$FILE1 $DEST_DIR1
        mv $DIR2/$FILE1 $DEST_DIR2
        echo "  Done moving files" >> $RESULT

    fi
done

for FILE2 in `ls $DIR2`
do
    if [ ! -f $DIR1/$FILE2 ]; then
        echo "  $FILE2 exists in $DIR2 but not found in $DIR1. Skipping file." >> $RESULT
    fi
done

echo "  Done comparing." >> $RESULT
# NEW: zip the file list of differing files
zip $DEST_DIR1/download.zip -@ < different.txt
mail -a $DEST_DIR1/download.zip [email protected]

相关内容