Shell Scripting: Check File Size ( Find File Size )

last updated in Categories , , , , , , , ,

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:


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:


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

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


Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

9 comment

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

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

  2. 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 ?


    1. Thanks for giving this command, for some reason stat -c option is not working on my mac terminal but this command does.

  3. Does Android bash support this idiom?:

    IFS=’ ‘
    set -A size `ls -s “$1″`

    Still, have a question? Get help on our forum!