如何使用 Bash 检查文件的大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5920333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 20:29:40  来源:igfitidea点击:

How to check size of a file using Bash?

bash

提问by user349418

I've got a script that checks for 0-size, but I thought there must be an easier way to check for file sizes instead. I.e. file.txtis normally 100k; how to make a script check if it is less than 90k (including 0), and make it do wget a new copy because the file is corrupt in this case.

我有一个检查 0 大小的脚本,但我认为必须有一种更简单的方法来检查文件大小。即file.txt通常是100k;如何使脚本检查它是否小于 90k(包括 0),并使其执行 wget 一个新副本,因为在这种情况下文件已损坏。

What I'm currently using..

我目前在用的..

if [ -n file.txt ]
then
 echo "everything is good"
else
 mail -s "file.txt size is zero, please fix. " [email protected] < /dev/null
 # Grab wget as a fallback 
 wget -c https://www.server.org/file.txt -P /root/tmp --output-document=/root/tmp/file.txt
 mv -f /root/tmp/file.txt /var/www/file.txt
fi

回答by Mikel

[ -n file.txt ]doesn't check its size, it checks that the string file.txtis non-zero length, so it will always succeed.

[ -n file.txt ]不检查它的大小,它检查字符串file.txt是非零长度,所以它总是会成功。

If you want to say "size is non-zero", you need [ -s file.txt ].

如果你想说“大小非零”,你需要[ -s file.txt ].

To get a file's size, you can use wc -cto get the size (file length) in bytes:

要获取文件的大小,您可以使用wc -c以字节为单位获取大小(文件长度):

file=file.txt
minimumsize=90000
actualsize=$(wc -c <"$file")
if [ $actualsize -ge $minimumsize ]; then
    echo size is over $minimumsize bytes
else
    echo size is under $minimumsize bytes
fi

In this case, it sounds like that's what you want.

在这种情况下,听起来这就是您想要的。

But FYI, if you want to know how much disk space the file is using, you could use du -kto get the size (disk space used) in kilobytes:

但是仅供参考,如果您想知道文件使用了多少磁盘空间,您可以使用du -k以千字节为单位获取大小(使用的磁盘空间):

file=file.txt
minimumsize=90
actualsize=$(du -k "$file" | cut -f 1)
if [ $actualsize -ge $minimumsize ]; then
    echo size is over $minimumsize kilobytes
else
    echo size is under $minimumsize kilobytes
fi

If you need more control over the output format, you can also look at stat. On Linux, you'd start with something like stat -c '%s' file.txt, and on BSD/Mac OS X, something like stat -f '%z' file.txt.

如果您需要更多地控制输出格式,您还可以查看stat. 在 Linux 上,您可以从stat -c '%s' file.txt类似stat -f '%z' file.txt.

回答by Daniel C. Sobral

It surprises me that no one mentioned statto check file size. Some methods are definitely better: using -sto find out whether the file is empty or not is easier than anything else if that's all you want. And if you want to findfiles of a size, then findis certainly the way to go.

令我惊讶的是,没有人提到stat检查文件大小。有些方法肯定更好:-s如果您只需要,那么使用它来确定文件是否为空比其他任何方法都容易。如果你想找到一个大小的文件,那么find肯定是要走的路。

I also like dua lot to get file size in kb, but, for bytes, I'd use stat:

我也很喜欢du以 kb 为单位获取文件大小,但是,对于字节,我会使用stat

size=$(stat -f%z $filename) # BSD stat

size=$(stat -c%s $filename) # GNU stat?

回答by fstab

alternative solution with awk and double parenthesis:

带有 awk 和双括号的替代解决方案:

FILENAME=file.txt
SIZE=$(du -sb $FILENAME | awk '{ print  }')

if ((SIZE<90000)) ; then 
    echo "less"; 
else 
    echo "not less"; 
fi

回答by gniourf_gniourf

If your findhandles this syntax, you can use it:

如果您find处理此语法,则可以使用它:

find -maxdepth 1 -name "file.txt" -size -90k

This will output file.txtto stdout if and only if the size of file.txtis less than 90k. To execute a script scriptif file.txthas a size less than 90k:

file.txt当且仅当 的大小file.txt小于 90k 时,这才会输出到 stdout 。script如果file.txt大小小于 90k,则执行脚本:

find -maxdepth 1 -name "file.txt" -size -90k -exec script \;

回答by BananaNeil

If you are looking for just the size of a file:

如果您只是在寻找文件的大小:

$ cat $file | wc -c
> 203233

回答by Neil McGill

This works in both linux and macos

这适用于 linux 和 macos

function filesize
{
    local file=
    size=`stat -c%s $file 2>/dev/null` # linux
    if [ $? -eq 0 ]
    then
        echo $size
        return 0
    fi

    eval $(stat -s $file) # macos
    if [ $? -eq 0 ]
    then
        echo $st_size
        return 0
    fi

    return -1
}

回答by Neil McGill

statappears to do this with the fewest system calls:

stat似乎用最少的系统调用来做到这一点:

$ set debian-live-8.2.0-amd64-xfce-desktop.iso

$ strace stat --format %s  | wc
    282    2795   27364

$ strace wc --bytes  | wc
    307    3063   29091

$ strace du --bytes  | wc
    437    4376   41955

$ strace find  -printf %s | wc
    604    6061   64793

回答by user6336835

python -c 'import os; print (os.path.getsize("... filename ..."))'

portable, all flavours of python, avoids variation in stat dialects

可移植的,所有风格的python,避免统计方言的变化

回答by mivk

For getting the file size in both Linux and Mac OS X (and presumably other BSDs), there are not many options, and most of the ones suggested here will only work on one system.

要在 Linux 和 Mac OS X(可能还有其他 BSD)中获取文件大小,选项不多,这里建议的大多数选项只能在一个系统上运行。

Given f=/path/to/your/file,

给定f=/path/to/your/file

what does work in both Linux and Mac's Bash:

什么在 Linux 和 Mac的 Bash 中都有效:

size=$( perl -e 'print -s shift' "$f" )

or

或者

size=$( wc -c "$f" | awk '{print }' )

The other answers work fine in Linux, but not in Mac:

其他答案在 Linux 中工作正常,但在 Mac 中无效:

  • dudoesn't have a -boption in Mac, and the BLOCKSIZE=1 trick doesn't work ("minimum blocksize is 512", which leads to a wrong result)

  • cut -d' ' -f1doesn't work because on Mac, the number may be right-aligned, padded with spaces in front.

  • du-b在 Mac中没有选项,并且 BLOCKSIZE=1 技巧不起作用(“最小块大小为 512”,这会导致错误的结果)

  • cut -d' ' -f1不起作用,因为在 Mac 上,数字可能是右对齐的,前面有空格。

So if you need something flexible, it's either perl's -soperator , or wc -cpiped to awk '{print $1}'(awk will ignore the leading white space).

所以如果你需要一些灵活的东西,它要么perl-soperator ,要么是wc -c管道awk '{print $1}'(awk 将忽略前导空格)。

And of course, regarding the rest of your original question, use the -lt(or -gt) operator :

当然,对于原始问题的其余部分,请使用-lt(or -gt) 运算符:

if [ $size -lt $your_wanted_size ]; thenetc.

if [ $size -lt $your_wanted_size ]; then等等。

回答by G-Man Says 'Reinstate Monica'

Based on gniourf_gniourf's answer,

基于 gniourf_gniourf 的回答,

find "file.txt" -size -90k

will write file.txtto stdout if and only if the size of file.txtis less than 90K, and

file.txt当且仅当 的大小file.txt小于 90K 时才会写入标准输出,并且

find "file.txt" -size -90k -exec command \;

will execute the command commandif file.txthas a size less than 90K.? I have tested this on Linux.? From find(1),

command如果file.txt大小小于 90K,将执行该命令。?我已经在 Linux 上测试过了。?从find(1),

…? Command-line arguments following (the -H, -Land -Poptions) are taken to be names of files ordirectories to be examined, up to the first argument that begins with ‘-', …

……?后面的命令行参数(the -H,-L-Poptions)被视为要检查的文件或目录的名称,直到第一个以“-”开头的参数,...

(emphasis added).

(强调)。