I couldn't find this question here. How do compare file sizes of two files, then do something only if the two files are of different sizes, in Bash?
To complement @Steve Bennett's helpful answer:
The stat
options indeed vary across platforms; it seems that the POSIX standard doesn't mandate a stat
utility (only a library function).
Here's a bash
function that works on both Linux and BSD-derived OSs, including OSX:
# SYNOPSIS
# fileSize file ...
# DESCRIPTION
# Returns the size of the specified file(s) in bytes, with each file's
# size on a separate output line.
fileSize() {
local optChar='c' fmtString='%s'
[[ $(uname) =~ Darwin|BSD ]] && { optChar='f'; fmtString='%z'; }
stat -$optChar "$fmtString" "$@"
}
Sample use:
if (( $(fileSize FILE1.txt) != $(fileSize FILE2.txt) )); then
echo "They're different."
fi