View size of items in a directory

View size of items in a directory

One may want to see the disk space used by each item (be it subdirectory or file) in a directory in a Linux environment. There are several ways to do that:

for f in `ls`; do du -hs $f; done

This works in most cases but has the minus that it fails if any of the items have spaces in their names. A workaround for names with spaces is to temporarily replace the IFS environment settings:

SAVEIFS=$IFS; IFS=$(echo -en "\n\b"); for f in `ls`; do du -hs $f; done; IFS=$SAVEIFS

An other alternative is to use this sequence of commands (with the downside that find is not as efficient as ls in folders with a lot of items)

for f in \'find . -maxdepth 1 -type f -printf \'%f\n\'\'; do du -hs $f; done

or even

du -k . | sort -nr | more

which displays all folders, including subfolders.

Leave a Reply