Bash – How to store the human-friendly size of a file in a variable

bashfilesshell-scriptsize;

Basically what I want to do is to make a script that will output all the files and their sizes in the directory which have size more than a threshold value (2.2 GB in my case). I tried using the stat command as below

a=$(stat -c '%s' example.txt)

but this will store the file size in bytes. What I want is to store and display the size in human readable format(MB,GB). I was also thinking to store the output of ls -lah and then trim the result so as to store only name and size but that seemed a tedious task. Is there other anyway to do this apart from storing the result in bytes and then doing arithmetic operations on it.

Best Answer

Since you're already using GNU tools, see numfmt from GNU coreutils:

$ stat -c %s file
310776
$ stat -c '%s' file | numfmt --to=si
311K
$ stat -c '%s' file | numfmt --to=iec
304K
$ stat -c '%s' file | numfmt --to=iec-i
304Ki
$ stat -c '%s' file | numfmt --to=si --suffix=B
311KB

With ksh93:

$ size=$(stat -c %s file)
$ printf "%#d %#i\n" "$size" "$size"
311k 304Ki

Or if built with the ls builtin (which you can also get as a standalone utility in the ast-open package):

$ type ls
ls is a shell builtin version of /opt/ast/bin/ls
$ ls -Z '%#(size)d %#(size)i' file
311k 304Ki
Related Question