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?
Asked
Active
Viewed 4,947 times
3 Answers
7
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

chepner
- 497,756
- 71
- 530
- 681
-
Can I assign the exit status of cpm to some variable in bash? – kulan May 02 '14 at 13:27
-
`var=$?`; just after `cmp
` -
this will also work `if (cmp file1 file2); then echo "same"; else echo "not"; fi` – Avinash Raj May 02 '14 at 13:36
-
1@AvinashRaj The parentheses are not necessary. – chepner May 02 '14 at 14:18
-
Shorthand for if/then/else without a variable: `cmp file1 file2 && echo "Files are identical" || echo "Files are different"` – Cole Tierney May 02 '14 at 14:40
-
A dangerous shorthand if used improperly; this works because `echo` always exits 0, but if the command following `&&` fails, the command following `||` is executed as well. `a && { b || true; } || c` is more correct (but uglier). – chepner May 02 '14 at 14:54
2
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"

Avinash Raj
- 172,303
- 28
- 230
- 274

pgl
- 7,551
- 2
- 23
- 31
0
If you just need to display the result, you can also use diff -q -s file1 file2
:
- The
-q
option (AKA--brief
) makesdiff
work similarly tocmp
, 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 andcmp
). - The
-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).

NotEnoughData
- 188
- 3
- 8