Last Updated: December 04, 2017
·
38.8K
· janosgyerik

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

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 ·

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

over 1 year ago ·

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

THANKS!

-->S.

over 1 year ago ·