[linux] Portable way to get file size (in bytes) in shell?

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?

This question is related to linux bash shell solaris

The answer is


on linux you can use du -h $FILE, does that work on solaris too?


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.


There is a trick in Solaris I have used, if you ask for the size of more than one file it returns just the total size with no names - so include an empty file like /dev/null as the second file:

eg command fileyouwant /dev/null

I can't rememebr which size command this works for ls/wc/etc - unfortunately I don't have a solaris box to test it.


You can use find command to get some set of files (here temp files are extracted). Then you can use du command to get the file size of each file in human readable form using -h switch.

find $HOME -type f -name "*~" -exec du -h {} \;

OUTPUT:

4.0K    /home/turing/Desktop/JavaExmp/TwoButtons.java~
4.0K    /home/turing/Desktop/JavaExmp/MyDrawPanel.java~
4.0K    /home/turing/Desktop/JavaExmp/Instream.java~
4.0K    /home/turing/Desktop/JavaExmp/RandomDemo.java~
4.0K    /home/turing/Desktop/JavaExmp/Buff.java~
4.0K    /home/turing/Desktop/JavaExmp/SimpleGui2.java~

if you have Perl on your Solaris, then use it. Otherwise, ls with awk is your next best bet, since you don't have stat or your find is not GNU find.


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)


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, ...


You first Perl example doesn't look unreasonable to me.

It's for reasons like this that I migrated from writing shell scripts (in bash/sh etc.) to writing all but the most trivial scripts in Perl. I found that I was having to launch Perl for particular requirements, and as I did that more and more, I realised that writing the scripts in Perl was probably a more powerful (in terms of the language and the wide array of libraries available via CPAN) and more efficient way to achieve what I wanted.

Note that other shell-scripting languages (e.g. python/ruby) will no doubt have similar facilities, and you may want to evaluate these for your purposes. I only discuss Perl since that's the language I use and am familiar with.


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.


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:

__ln=( $( ls -Lon "$1" ) )
__size=${__ln[3]}
echo "Size is: $__size bytes"

If required, simplify ls arguments, and adjust offset in ${__ln[3]}.

Note: will follow symlinks.


When processing ls -n output, as an alternative to ill-portable shell arrays, you can use the positional arguments, which form the only array and are the only local variables in standard shell. Wrap the overwrite of positional arguments in a function to preserve the original arguments to your script or function.

getsize() { set -- $(ls -dn "$1") && echo $5; }
getsize FILE

This splits the output of ln -dn according to current IFS environment variable settings, assigns it to positional arguments and echoes the fifth one. The -d ensures directories are handled properly and the -n assures that user and group names do not need to be resolved, unlike with -l. Also, user and group names containing whitespace could theoretically break the expected line structure; they are usually disallowed, but this possibility still makes the programmer stop and think.


Did you try du -ks | awk '{print $1*1024}'. That might just work.


If you use find from GNU fileutils:

size=$( find . -maxdepth 1 -type f -name filename -printf '%s' )

Unfortunately, other implementations of find usually don't support -maxdepth, nor -printf. This is the case for e.g. Solaris and macOS find.


Examples related to linux

grep's at sign caught as whitespace How to prevent Google Colab from disconnecting? "E: Unable to locate package python-pip" on Ubuntu 18.04 How to upgrade Python version to 3.7? Install Qt on Ubuntu Get first line of a shell command's output Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running? Run bash command on jenkins pipeline How to uninstall an older PHP version from centOS7 How to update-alternatives to Python 3 without breaking apt?

Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to solaris

How to get rid of the "No bootable medium found!" error in Virtual Box? What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK] sed edit file in place Windows equivalent of linux cksum command How to use S_ISREG() and S_ISDIR() POSIX Macros? Test if remote TCP port is open from a shell script Portable way to get file size (in bytes) in shell? Get the date (a day before current time) in Bash How to set the From email address for mailx command? How to determine the IP address of a Solaris system