help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Check if file size greater than a small number?


From: Kerin Millar
Subject: Re: Check if file size greater than a small number?
Date: Wed, 9 Mar 2022 18:33:09 +0000

On Wed, 9 Mar 2022 11:42:11 -0600
Dennis Williamson <dennistwilliamson@gmail.com> wrote:

> On Wed, Mar 9, 2022 at 11:10 AM Peng Yu <pengyu.ut@gmail.com> wrote:
> 
> >
> > https://stackoverflow.com/questions/5920333/how-can-i-check-the-size-of-a-file-using-bash
> >
> > I see things like the above that call an external program or cat all
> > the file content to check the size of a file.
> >
> > But if my goal is just to know whether the file size is greater than a
> > smaller (say 40). What is the most efficient way to do so in bash?
> >
> > --
> > Regards,
> > Peng
> >
> >
> size=41
> filename=testfile
> read -n "$size" < "$filename"
> if ((${#REPLY} >= size)) ...

Assuming that the goal is consider the file size in units of bytes, this won't 
be reliable.

$ locale | grep LC_CTYPE
LC_CTYPE="en_GB.UTF-8"
$ printf '\xe2\x98\x83' > sample
$ stat -c%s sample
3
$ read -n3 -r < sample; echo "${#REPLY}"
1
$ printf '\n123' > sample
$ read -n3 -r < sample; echo "${#REPLY}"
0

It can be improved by coercing the C locale and using -N instead of -n. Even 
then, it won't be able to handle binary.

$ printf '.\0........' > sample
$ LC_ALL=C
$ read -N3 -r < sample
$ unset LC_ALL
$ stat -c%s sample
10
$ echo "${#REPLY}"
3

For those reasons, I'd recommend against using this method if you need to be 
able to account for the presence of NUL bytes. In that case, one option would 
be to use find.

$ filename=sample
$ printf '..........' > "$filename"
$ size=9
$ read -r < <(find "$filename" -type f -size +"$size"c 2>/dev/null) && echo 
"Size is greater than $size bytes"

Another option would be to use a platform-specific stat(1) utility. Both 
methods will incur a subshell and an additional fork but they do, at least, go 
by the st_size field rather than resort to counting bytes.

-- 
Kerin Millar



reply via email to

[Prev in Thread] Current Thread [Next in Thread]