Bash – get approximate size of directory (recursively including all files and sub-directories)

bash

Is there a way to quickly get an accurate size for a directory (including, recursively, all its sub-directories)? I don't want the sizes of the subdirs, I just mean that they should be recursively included in the total size reported.

Failing that, a way to get an approximate size? I am thinking something along the lines of df that produces a quick response for the entire file system, but this time for a specific directory (and it's subdirectories).

Solutions using du seem to take ages when given a directory contains thousands of sub-dirs.

Best Answer

I find this is quite useful.

du -sm Directory

or to get a breakdown of inside directories

du -sm Directory/*

and then with a sort if it's got many subdirs

du -sm Directory/* | sort -n 

The reason I use the -m option is to ensure I get a megabyte output. I find this is easier for me to compare visually (when I'm not getting a mixture of units eg compare 999 KB and 1MB vs 999000MB and 1000000MB), the added benefit is that you can pass output into sort.

Put it all in the background and redirect output, it's going to take time what ever method one uses, it's a traverse of many files which will take time.

du -sm Directory/* | sort -nr > ~/cacheDu.log &

Note out the reverse sort so the big ones are at the beginning. Add this to cron run every n mins.

Then with an alias ducache, you've got a fairly up-to-date directory usage.

export alias ducache='head -n 15 ~/cacheDu.log'
Related Question