du -h --max-depth=1 takes long time

Özzesh picture Özzesh · Apr 16, 2013 · Viewed 44.8k times · Source

When I try to calculate the size of files and directory inside the directory it takes longer time. The command I used is du -ch --max-depth=1.

Is there any other way to calculate total size of files and folder?

Thanks

Answer

Jacob picture Jacob · Apr 16, 2013

The command du retrieves the disk usage of all files in the directory and all sub-directories (recursively) by default. So the time spent by du relates to the number of files analyzed. The options -s or --summarize and --max-depth just influence the output of the command (and not the scanning itself).

Some du options that limit the file scanning are --one-file-system, --exclude, and --exclude-from.

If you don't want to recurse into the sub-dirs, you can use find instead, which gives you much more control about which files to analyze. But it can't sum up disk usage recursivly.

find /path/to/dir -maxdepth 1 -printf  "%k\t%p\n"

Notice, that %k always return the disk usage in 1k blocks and the reported disk usage of sparse files might be less or slightly larger then the file size returned by %s of the ls command. Thus '%k' behaves like the du command for single files.

If you want to combine the features of find and du you can combine both of them by something like.

find . -maxdepth 1 -name "xyz*" -print0 | du --files0-from=-