pdkkxq
Last Updated: February 25, 2016
·
13.24K
· janosgyerik
32ef4e3e388cbadc756a008cade3ee6a

How to check in bash if file size is greater than N

You can do this using the find command and the [[ builtin,
wrapped in a one-liner like this:

[[ $(find /path/to/file -type f -size +51200c 2>/dev/null) ]] && echo true || echo false
  • The find takes care of two things at once: checks if file exists and size is greater than 51200 bytes.
  • We redirect stderr to /dev/null to hide the error message when the file doesn't exist.
  • The output of find will be non-blank if the file matched both conditions, otherwise it will be blank.
  • The [[ ... ]] evaluates to true or false if the output of find is non-blank or blank, respectively.

You can use this in if conditions, for example:

if [[ $(find /path/to/file -type f -size +51200c 2>/dev/null) ]]; then
    somecmd
fi

3 Responses
Add your response

17542
None

Thanks for the good tip, but it should be then instead of do at the end of the if line I think. Took me a few minutes before seeing the mistake.

over 1 year ago ·
17545
32ef4e3e388cbadc756a008cade3ee6a

Ouch, thanks @wvdv2002, well spotted! (I fixed it now)

over 1 year ago ·
21244
0 5kcgs7i2xkuulvscftlcsdql0grsl9scblngsd8uhffwmtsgdntlqsqcauuk aumkp8 veocqw v

Excellent solution - this got our test harness working again and we're back on schedule.

THANKS!

-->S.

over 1 year ago ·