检查Bash中两个文件的大小是否不同

时间:2014-04-28 03:03:31

标签: bash filesize stat

我在这里找不到这个问题。如何比较两个文件的文件大小,然后只在两个文件大小不同的情况下做一些事情,在Bash中?

2 个答案:

答案 0 :(得分:4)

Bash似乎没有内置,但您可以使用stat

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

stat的确切参数可能因操作系统而异。

答案 1 :(得分:4)

补充@Steve Bennett的有用答案:

stat选项确实因平台而异;似乎 POSIX标准没有强制要求stat 实用程序 (只有库函数)。

这是一个 bash函数,适用于Linux和BSD派生的操作系统,包括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" "$@"
}

样品使用:

if (( $(fileSize FILE1.txt) != $(fileSize FILE2.txt) )); then
  echo "They're different."
fi
相关问题