Shell Person Help me keep the shell people alive.

16Dec/090

BASH – Get Size of Directory in "ls -l" Output

flowring cabbage regular by abundantlyabove29 (C) via Flickr

(The above photo is "flowring cabbage regular", by abundantlyabove29 (C) via Flickr).

UPDATE: I've written a newer and much better version of this script. You can find it at: http://www.shellperson.net/show-directory-size-with-ls/

I found a function like this a long time ago in some forum, but I remember it not working with filenames that include spaces. There's almost certainly a better and more-efficient way of doing this, but here's draft one.

This will output the same data as "ls -lh", in almost the exact same format, except directories will show the size of the sum of their contents (du -sh) instead of the 4.0K of space the directory "file" takes up. The only noticeable difference in format is that there is a slightly larger gap between the size and the date columns.

#!/bin/bash
## mimic "ls -l" except display size of sum of directory's contents
for x in *; do echo -e "$(ls -lL | grep -w "$x" | cut -d ' ' -f 1-4) $(du -sh "$x" | cut -d '	' -f 1)" "\t" "$(ls -lL | grep -w "$x" | cut -d ' ' -f 5-20 | sed s/^\ *// | cut -d ' ' -f 2-20)"; done

It's hard to enter code in a presentable way in wordpress - and this code doesn't appear perfectly. Note that the multiple-space gap that delimits (-d) the second "cut" command is a tab. You can add a tab at the command line by using CTRL+v followed by TAB. The code does work if you use the copy-to-clipboard button on the code block.

I saved this as "lsd", made it executable, and put it in a directory in my $PATH (~/bin).