# If use while read loop, the array in while statement will # auto set to null after the loop, so i use for statement # instead the while, and so, i modify the variable IFS to # $'\n'.
# md5sum format: MD5 /path/to/file # such as:80748c3a55b726226ad51a4bafa1c4aa /etc/fstab for line in `md5sum "$@"` do index=${line%% *} file=${line##* } md5_array[$index]="$file ${md5_array[$index]}" done
# Traverse the md5_array for i in ${!md5_array[@]} do echo -e "the same file with md5: $i\n--------------\n`echo ${md5_array[$i]}|tr ' ' '\n'`\n" done
为了测试该脚本,先复制几个文件,并修改其中几个文件的内容,例如:
1 2 3
[root@xuexi ~]# for i in `seq -s' ' 6`;do cp -a /etc/fstab /tmp/fs$i;done [root@xuexi ~]# echo ha >>/tmp/fs4 [root@xuexi ~]# echo haha >>/tmp/fs5
[root@xuexi tmp]# ./md5.sh /tmp/fs[1-6] the same file with md5: a612cd5d162e4620b442b0ff3474bf98 -------------------------- /tmp/fs6 /tmp/fs3 /tmp/fs2 /tmp/fs1
the same file with md5: 80748c3a55b726226ad51a4bafa1c4aa -------------------------- /tmp/fs4
the same file with md5: 30dd43dba10521c1e94267bbd117877b -------------------------- /tmp/fs5
更具通用性地比较方法:比较多个目录下的同名文件。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
[root@xuexi tmp]# find /tmp -type f -name "fs[0-9]" -print0 | xargs -0 ./md5.sh the same file with md5:a612cd5d162e4620b442b0ff3474bf98 -------------------------- /tmp/fs6 /tmp/fs3 /tmp/fs2 /tmp/fs1
the same file with md5:80748c3a55b726226ad51a4bafa1c4aa -------------------------- /tmp/fs4
the same file with md5:30dd43dba10521c1e94267bbd117877b -------------------------- /tmp/fs5