Is there any ls
parameter which I can use to display file-size for directories as well.
When I do ls -s
, it shows me block-size
(4k always) instead of directory size.
Thank you!!!
Edit – Partial achievement
As told by @Arronical, Command du -sh *
shows the files & directories with their size. One small enhancement I am looking is to show directory in different colour like ls
shows. Any ideas. Thank you. 🙂
Best Answer
Basic idea
One could emulate the
ls -l
with find. For instance, like withfind
command that will rundu
per each directory and file found:Sample output ( side note , here I am using
-type d
to show listing for directories only for demo purpose; this command without-type d
will list all files and directories):NOTE:
find
has-ls
flag, which I am not using here, for the same reason as OP stated - it shows canonical 4096 bytesSimplification
This command itself can be turned into an alias, something like
ls2
or a function, which then also could take$1
argument. For instance, here's what I've placed into my.bashrc
and how it works:Sample runs:
Output organization
There's no way to colorize the output natively in
find
, which is designed specifically to parse filenames.ls
coloring comes from special characters included into the output, which we don't really want.However, one could read the permissions. The leading
-
in-rwxr-xr-x
means it's a regular file, and leadingd
indrwxr-xr-x
means directory.find
also has the handy-type
flag, which we can use as well to filter the output. For instance, here's edited version oflscwd
And sample output:
The output sometimes can be very lengthy , so I would suggest using this function in conjunction with
less
paging utility. Just pipe the output like solscwd2 | less
About ls and stat
Why do people always suggest
du
? izx in his brief and awesome answer explained it way better that I could, but in a nutshell, on Unix and Linux everything is a file, and in the reality directory is a file with a list of files linked to it. Thus,stat
andls
give size of that special file, not the total amount of all the files linked to the directory. Butdu
is what saves the day. Note what the description inman du
says :du
utility jumps down into each directory and sums up file size of each file there. Way different from whatls
andstat
do.So the purpose of each utility is very different.
ls
is doing exactly what it is asked to do - list file sizes, and coming from Windows world we understand directory's size as being this "bag" whose size depends on the amount of apples in it, if I may use it for comparison. Unix is slightly different, yes, but it is realistic. Maybe it doesn't cater to user needs that much, but it makes sense in real, physical sense.On a side note, block size is by default 4k, but once file grows over 4k, the filesystem will need to allocate more space. For instance, my home folder has 73GB in total size of all files there. What about the block size of the directory ?