Using File#length() method A simple solution is to call the File#length() method that returns the size of the file in bytes. To get the file size in MB, you can divide the length (in bytes) by 1024 * 1024 .
Getting file size using find command find "/etc/passwd" -printf "%s" find "/etc/passwd" -printf "%s\n" fileName="/etc/hosts" mysize=$(find "$fileName" -printf "%s") printf "File %s size = %d\n" $fileName $mysize echo "${fileName} size is ${mysize} bytes."
What we need is to open the terminal and type du -sh file name in the prompt. The file size will be listed on the first column. The size will be displayed in Human Readable Format. This means we can see file sizes in Bytes, Kilobytes, Megabytes, Gigabytes, etc.
Using the ls Command–l – displays a list of files and directories in long format and shows the sizes in bytes.
wc -c < filename
(short for word count, -c
prints the byte count) is a portable, POSIX solution. Only the output format might not be uniform across platforms as some spaces may be prepended (which is the case for Solaris).
Do not omit the input redirection. When the file is passed as an argument, the file name is printed after the byte count.
I was worried it wouldn't work for binary files, but it works OK on both Linux and Solaris. You can try it with wc -c < /usr/bin/wc
. Moreover, POSIX utilities are guaranteed to handle binary files, unless specified otherwise explicitly.
I ended up writing my own program (really small) to display just the size. More information here: http://fwhacking.blogspot.com/2011/03/bfsize-print-file-size-in-bytes-and.html
The two most clean ways in my opinion with common Linux tools are:
$ stat -c %s /usr/bin/stat
50000
$ wc -c < /usr/bin/wc
36912
But I just don't want to be typing parameters or pipe the output just to get a file size, so I'm using my own bfsize.
Even though du
usually prints disk usage and not actual data size, GNU coreutils du
can print file's "apparent size" in bytes:
du -b FILE
But it won't work under BSD, Solaris, macOS, ...
Finally I decided to use ls, and bash array expansion:
TEMP=( $( ls -ln FILE ) )
SIZE=${TEMP[4]}
it's not really nice, but at least it does only 1 fork+execve, and it doesn't rely on secondary programming language (perl/ruby/python/whatever)
BSDs have stat
with different options from the GNU coreutils one, but similar capabilities.
stat -f %z <file name>
This works on macOS (tested on 10.12), FreeBSD, NetBSD and OpenBSD.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With