Shell Scripting: Check File Size ( Find File Size )

Posted on in Categories , , , , , , , , last updated February 24, 2009

How do I find out file size under UNIX / Linux operating system and store the same to a variable called s?

There are various ways and command tricks to find out file size under UNIX / Linux shell.

stat command example

You can display file or file system status with GNU/stat command. The -c option can be used to get specific information about file such as size in bytes:
$ stat -c %s fw8ben.pdf
Sample output:

74777

Refer to your local stat command man page for exact syntax, for example, FreeBSD stat works as follows:
$ stat -s file.txt

ls command example

Use ls command as follows to get human readable format:
$ ls -lah fw8ben.pdf | awk '{ print $5}'
Sample output:

74K

You can store output to a variable:
$ s=$(ls -lah idg.fw8ben.pdf | awk '{ print $5}')
$ echo $s

OR
$ s=$( stat -c %s fw8ben.pdf)
$ echo $s

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

Share this on (or read 9 comments/add one below):

9 comment

Leave a Comment