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

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 to 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 an if statement?

Asked By: Ravi

||

If you want to query one single file at a time, stat is a general-purpose tool for querying various attributes of a particular file, including size among many others.

FileName="foo"
FSize=1048576
if [ $(stat -f %z "$FileName") -gt $FSize ]; then
    printf "File %s is larger than %d bytes.n" "$FileName" $FSize
fi

If what you’re really looking for is a way to query a large number of files, and pull out the names of only those files which are over a certain size, then find may be what you want.

Given a group of files located in DIRECTORY, this will find those files larger than FSize bytes:

DIRECTORY="/path/to/your/files"
FSize="1M"
find $DIRECTORY -type f -size +$FSize
Answered By: Jim L.

Using find on a specific file at $filepath:

if [ -n "$(find "$filepath" -prune -size +1000000c)" ]; then
    printf '%s is strictly larger than 1 MBn' "$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 MBn' {} +

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.

Answered By: Kusalananda
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.