如何使用Bash检查文件大小? [英] How to check size of a file using Bash?

查看:217
本文介绍了如何使用Bash检查文件大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.txt is 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.

我目前正在使用什么.

if [ -n file.txt ]
then
 echo "everything is good"
else
 mail -s "file.txt size is zero, please fix. " myemail@gmail.com < /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

推荐答案

[ -n file.txt ]不检查其大小,而是检查字符串file.txt的长度是否为非零,因此它将始终成功.

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

如果要说大小不为零",则需要[ -s file.txt ].

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

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

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

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.

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

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

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

如果您需要对输出格式的更多控制,还可以查看stat.在Linux上,您将以stat -c '%s' file.txt之类的东西开始,而在BSD/Mac OS X上,您将以stat -f '%z' file.txt之类的东西开始.

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.

这篇关于如何使用Bash检查文件大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆