Bash Scripting – How to Get the Size of a File

bashfilesshell

How can I get the size of a file in a bash script?

How do I assign this to a bash variable so I can use it later?

Best Answer

Your best bet if on a GNU system:

stat --printf="%s" file.any

From man stat:

%s total size, in bytes

In a bash script :

#!/bin/bash
FILENAME=/home/heiko/dummy/packages.txt
FILESIZE=$(stat -c%s "$FILENAME")
echo "Size of $FILENAME = $FILESIZE bytes."

NOTE: see @chbrown's answer for how to use stat in terminal on Mac OS X.

Related Question