'How to check if a file's size is greater than a certain value in Bash

How do I achieve the following goal:

  • I need to check the size of a file
  • Then compare this file size to a fixed number using an if condition and corresponding conditional statement

So far, I have the following:

#!/bin/bash

# File to consider
FILENAME=./testfile.txt

# MAXSIZE is 5 MB
MAXSIZE = 500000

# Get file size
FILESIZE=$(stat -c%s "$FILENAME")
# Checkpoint
echo "Size of $FILENAME = $FILESIZE bytes."

# The following doesn't work
if [ (( $FILESIZE > MAXSIZE)) ]; then
    echo "nope"
else
    echo "fine"
fi

With this code, I can get the file name in the variable $FILESIZE, but I am unable to compare it with a fixed integer value.

#!/bin/bash
filename=./testfile.txt
maxsize=5
filesize=$(stat -c%s "$filename")
echo "Size of $filename = $filesize bytes."

if (( filesize > maxsize )); then
    echo "nope"
else
    echo "fine"
fi


Solution 1:[1]

You can use the find command to accomplish this as well. See the below examples.

You can change the stat command for any command you need.

ls -lh test.txt

-rw-r--r-- 1 root root 25M Jan 20 19:36 test.txt


find ~/test.txt -size 25M -exec stat '{}' \;

  File: '/root/test.txt'
  Size: 26214400        Blocks: 51200      IO Block: 4096   regular file
Device: fe04h/65028d    Inode: 402704      Links: 1
Access: (0644/-rw-r--r--)  Uid: (    0/    root)   Gid: (    0/    root)
Access: 2022-01-20 19:36:51.222371293 +0000
Modify: 2022-01-20 19:36:51.242373113 +0000
Change: 2022-01-20 19:36:51.242373113 +0000
 Birth: -

If the file does not have the size you are looking for, it won't do anything.

find ~/test.txt -size 99M -exec true \;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Peter Mortensen