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?

有帮助吗?

解决方案

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

其他提示

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"

If you just need to display the result, you can also use diff -q -s file1 file2:

  • The -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).
  • 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).

Source

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top