Can I use 'stat' to check file size?

QuestionsQuestions4 SkillsProPermissions of FilesOct, 29 2025
0185

Yes, you can use the stat command to check the size of a file in a Linux environment. The stat command provides detailed information about a file, including its size, permissions, and timestamps.

Checking File Size with stat

To check the size of a file, you can use the following command:

stat -c %s filename.txt

Explanation

  • stat: The command used to display file or filesystem status.
  • -c %s: This option specifies the output format. %s returns the size of the file in bytes.
  • filename.txt: Replace this with the name of the file you want to check.

Example

Here’s how you can use stat in practice:

# Check the size of example.txt
file_size=$(stat -c %s example.txt)

echo "The size of example.txt is $file_size bytes."

Using stat in a Script

You can also incorporate stat into a script to check if a file is empty:

#!/bin/bash
FILENAME="example.txt"

# Get the file size
file_size=$(stat -c %s "$FILENAME")

if [ "$file_size" -eq 0 ]; then
    echo "File $FILENAME is empty."
else
    echo "File $FILENAME is not empty and its size is $file_size bytes."
fi

Running the Script

  1. Save the script to a file, e.g., check_file_size.sh.
  2. Make it executable:
    chmod +x check_file_size.sh
    
  3. Run the script:
    ./check_file_size.sh
    

This script will check the size of example.txt and print whether it is empty or not, along with its size in bytes.

Feel free to ask if you have any further questions or need more examples!

0 Comments

no data
Be the first to share your comment!