On Linux, I use stat --format="%s" FILE
, but Solaris I have access to doesn't have stat command. What should I use then?
I'm writing Bash scripts, and can't really install any new software on the system.
I've considered already using:
perl -e '@x=stat(shift);print $x[7]' FILE
or even:
ls -nl FILE | awk '{print $5}'
But neither of these looks sensible - running Perl just to get file size? Or running 2 commands to do the same?
Even though
du
usually prints disk usage and not actual data size, GNU coreutilsdu
can print file's "apparent size" in bytes:But it won't work under BSD, Solaris, macOS, ...
You can use
find
command to get some set of files (here temp files are extracted). Then you can usedu
command to get the file size of each file in human readable form using-h
switch.OUTPUT:
Finally I decided to use ls, and bash array expansion:
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)
Cross platform fastest solution (only uses single fork() for ls, doesn't attempt to count actual characters, doesn't spawn unneeded awk, perl, etc).
Tested on MacOS, Linux - may require minor modification for Solaris:
If required, simplify ls arguments, and adjust offset in ${__ln[3]}.
Note: will follow symlinks.
If you use
find
from GNU fileutils:Unfortunately, other implementations of
find
usually don't support-maxdepth
, nor-printf
. This is the case for e.g. Solaris and macOSfind
.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.