Pregunta

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?

¿Fue útil?

Solución 2

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

Otros consejos

Bash doesn't seem to have this as a built in, but you can use stat.

if [ $(stat -c %s FILE1.txt) -ne $(stat -c %s FILE2.txt) ]; then 
   echo "They're different."
fi

The exact arguments to stat may vary on the OS.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top