Linux – Check If File Size Is Greater Than 1MB Using IF Condition

linuxsize;

By using ls -lh we can get the file size.

Is there any way i can check if the file size is greater than 1MB then print a message like below ( i may have files with different sizes like 100mb , 1gb,10gb, 100kb )

if [ $FileSize > 1MB ];
then
    echo "File size is grater than 1MB"
fi

Is there a way i can check the file size using IF statement , ( If this is already asked pls lemme know , as i didnt get any link to refer)

Best Answer

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.