Check if the file size greater than 1MB using IF condition

Using find on a specific file at $filepath:

if [ -n "$(find "$filepath" -prune -size +1000000c)" ]; then
    printf '%s is strictly larger than 1 MB\n' "$filepath"
fi

This uses find to query the specific file at $filepath for its size. If the size is greater than 1000000 bytes, find will print the pathname of the file, otherwise it will generate nothing. The -n test is true if the string has non-zero length, which in this case means that find outputted something, which in turns means that the file is larger than 1 MB.

You didn't ask about this: Finding all regular files that are larger than 1 MB under some $dirpath and printing a short message for each:

find "$dirpath" -type f -size +1000000c \
    -exec printf '%s is larger than 1 MB\n' {} +

These pieces of code ought be to portable to any Unix.


Note also that using < or > in a test will test whether the two involved strings sort in a particular way lexicographically. These operators do not do numeric comparisons. For that, use -lt ("less than"), -le ("less than or equal to"), -gt ("greater than"), or -ge ("greater than or equal to"), -eq ("equal to"), or -ne ("not equal to"). These operators do integer comparisons.

Tags:

Linux

Size