Portable way to get file size (in bytes) in shell?
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, ...