Shell Scripting: Check File Size ( Find File Size )

In shell scripting, you can check the size of a file using the stat command. The stat command displays file or file system status, including file size, in a user-readable format.

Here’s an example shell script that uses stat to find the size of a file:

#!/bin/bash

filename="/path/to/file.txt"

# check if file exists
if [ -e "$filename" ]
then
# get file size in bytes
size=$(stat -c "%s" "$filename")
# print the size in human-readable format
echo "File size is $(numfmt --to=iec-i --suffix=B $size)"
else
echo "File not found."
fi

In the above script, replace “/path/to/file.txt” with the path of the file you want to check. The if statement checks if the file exists. If it does, the script uses the stat command with the %s format specifier to get the file size in bytes. The numfmt command is then used to convert the size to a human-readable format (in this case, using binary prefixes like KiB, MiB, and GiB). Finally, the script prints the size to the console. If the file does not exist, the script prints an error message.

Leave a Comment