Reputation: 1391
cmp file1 file2
does nothing when the files are the same. So how do I print out that files are the same in shell script?
Upvotes: 6
Views: 5554
Reputation: 318
If you just need to display the result, you can also use diff -q -s file1 file2
:
-q
option (AKA --brief
) makes diff
work similarly to cmp
, so that it only checks whether the files are different or identical, without identifying the changes (Note: I don't know if there's a performance difference between this and cmp
).-s
option (AKA --report-identical-files
) makes it display a "Files file1 and file2 are identical" message rather than giving no output. When the files differ, a "Files file1 and file2 differ" message is shown either way (assuming -q
is used).Upvotes: 0
Reputation: 532418
The exit status of cpm
is zero if the files are identical, and non-zero otherwise. Thus, you can use something like
cmp file1 file2 && echo "Files are identical"
If you want to save the exit status, you can use something like the following instead:
cmp file1 file2
status=$?
if [[ $status = 0 ]]; then
echo "Files are the same"
else
echo "Files are different"
fi
Upvotes: 7
Reputation: 8031
Use the exit status code of cmp
. Exit codes of 0 mean they're the same:
$ cmp file1 file2; echo $?
0
In a script you can do something like this:
cmp file1 file2 && echo "same"
Upvotes: 2