检查Bash中的两个文件是否大小不同
我在这里找不到这个问题。如何在Bash中比较两个文件的文件大小,然后仅当两个文件大小不同时才执行操作?Bash似乎没有内置此功能,但您可以使用检查Bash中的两个文件是否大小不同,bash,filesize,stat,Bash,Filesize,Stat,我在这里找不到这个问题。如何在Bash中比较两个文件的文件大小,然后仅当两个文件大小不同时才执行操作?Bash似乎没有内置此功能,但您可以使用stat if [ $(stat -c %s FILE1.txt) -ne $(stat -c %s FILE2.txt) ]; then echo "They're different." fi stat的确切参数在操作系统上可能会有所不同。Bash似乎没有内置此参数,但您可以使用stat if [ $(stat -c %s FILE1.txt
stat
if [ $(stat -c %s FILE1.txt) -ne $(stat -c %s FILE2.txt) ]; then
echo "They're different."
fi
stat
的确切参数在操作系统上可能会有所不同。Bash似乎没有内置此参数,但您可以使用stat
if [ $(stat -c %s FILE1.txt) -ne $(stat -c %s FILE2.txt) ]; then
echo "They're different."
fi
stat
的确切参数可能因操作系统而异。补充@Steve Bennett的有用答案:
stat
选项确实因平台而异;似乎POSIX标准没有强制要求使用stat
实用程序(只有库函数)
这里有一个bash函数,可以在Linux和BSD派生的OSs(包括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
补充@Steve Bennett的有用答案:
stat
选项确实因平台而异;似乎POSIX标准没有强制要求使用stat
实用程序(只有库函数)
这里有一个bash函数,可以在Linux和BSD派生的OSs(包括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
是的,不幸的是,
stat
由于不是POSIX而非常不可移植(例如Solaris没有它)。唯一可移植的确定文件大小的方法是使用wc-c
,不幸的是,它可能读取整个文件。如果[FILE]
是一个常规文件(busybox
),则coreutils
实现使用fstat()
对其进行优化(busybox也用于此操作,但由于明显损坏而将其丢弃)。另一个选项是使用find
的-printf
功能,但这也是特定于GNU find
(但可能在没有stat
的平台上可用)。YMMV.是的,不幸的是,stat
由于不是POSIX而非常不可移植(例如Solaris没有它)。唯一可移植的确定文件大小的方法是使用wc-c
,不幸的是,它可能读取整个文件。如果[FILE]
是一个常规文件(busybox
),则coreutils
实现使用fstat()
对其进行优化(busybox也用于此操作,但由于明显损坏而将其丢弃)。另一个选项是使用find
的-printf
功能,但这也是特定于GNU find
(但可能在没有stat
的平台上可用)。YMMV。