Shell Scripting: Check File Size ( Find File Size )

by Vivek Gite on February 24, 2009 · 3 comments

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

Featured Articles:

Share this with other sys admins!
Facebook it - Tweet it - Print it -

{ 3 comments… read them below or add one }

1 marz February 25, 2009

s=$(du -h myfile | awk ‘{ print $1 }’)

“-h” == “print sizes in human readable format (e.g., 1K 234M 2G)”

Reply

2 tom July 29, 2010

Thanks for these tips.

Question: in — $ stat -c %s fw8ben.pdf —- what does %s do ? Any how does one refer to it i.e what is it ?

Tom

Reply

3 Raghu B R June 22, 2011

du -k Filename

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 13 + 2 ?
Please leave these two fields as-is:
Solve the simple math so we know that you are a human and not a bot.




Previous post:

Next post: