Diff several files, true if all not equal
With GNU diff, pass one of the files as an argument to --from-file
and any number of others as operand:
$ diff -q --from-file file1 file2 file3 file4; echo $?
0
$ echo >>file3
$ diff -q --from-file file1 file2 file3 file4; echo $?
Files file1 and file3 differ
1
You can use globbing as usual. For example, if the current directory contains file1
, file2
, file3
and file4
, the following example compares file2
, file3
and file4
to file1
.
$ diff -q --from-file file*; echo $?
Note that the “from file” must be a regular file, not a pipe, because diff will read it multiple times.
How about:
md5sum * | awk 'BEGIN{rc=1}NR>1&&$1!=last{rc=0}{last=$1}END{exit rc}'
Calculates the MD5 value for each file, then compares each entry with the next, if any are different, then return a zero (true) exit status. This would be much shorter if it returned false if different:
md5sum * | awk 'NR>1&&$1!=last{exit 1}{last=$1}'
There is no need to sort since we are just checking if any are different.
The following code should be fairly self explanatory. $#
is the number of file arguments, and shift
just consumes them one at a time. Uses cmp -s
for silent byte-wise comparison.
#!/bin/sh
# diffseveral
if [ $# -lt 2 ]; then
printf '%s\n' "Usage: $0 file1 file2 [files ...]" >&2
exit 2
fi
oldfile="$1"
shift
while [ $# -gt 0 ]; do
newfile="$1"
if ! cmp -s "$oldfile" "$newfile"; then
echo 'Files differ.'
exit 1;
fi
shift
done
echo 'All files identical.'
exit 0