42

I know I can use du -h to output the total size of a directory. But when it contains other subdirectories, the output would be something like:

du -h /root/test

.
.
.
.
24K   /root/test/1
64K   /root/test/2
876K  /root/test/3
1.1M  /root/test/4
15M   /root/test/5
17M   /root/test

I only want the last line because there are too many small directories in the /root/test directory. What can I do?

1
  • Just add the -s flag, du -sh /root/test
    – mathandy
    Jun 25, 2019 at 22:19

2 Answers 2

66

Add the --max-depth parameter with a value of 0:

du -h --max-depth=0 /root/test

Or, use the -s (summary) option:

du -sh /root/test

Either of those should give you what you want. For future reference, man du is very helpful.

5
  • 5
    +1 with a remark: certain implementations of du do not have the option --max-depth though (Busybox, for example). But the -s option does the trick in this case Oct 29, 2015 at 12:36
  • 5
    -s is standard, --max-depth is GNU specific. The short version (-d) will also work in FreeBSD. -h is not standard but supported by a few implementations. Oct 29, 2015 at 12:56
  • when using -s, sometimes I got warnings like: du: cannot access `/root/test/8393.jpg.tmp': No such file or directory. What should I do to ignore this? I mean, not solve the warning but don't let du to output it. Oct 29, 2015 at 13:46
  • 2
    @AwQiruiGuo: 2>/dev/null will cause stderr to be ignored Oct 29, 2015 at 16:45
  • Thanks! Remarks: On macOS 11 Big Sur the option needed for du is -d (as in "depth"). du -d 0 only gives you the size of your current directory (".") without listing the directories in it. du -d 1 if you want a list of directories in the current directory and the total size they consume. du -d 2 if you want to also get the sub-directories listed with their size too. And so on and so forth.
    – porg
    Mar 18, 2021 at 11:34
1

The tail and head command shall be used to display last and beginning of the list.

In this case use following command::

## Display the last ten items
du -h /root/test | tail 
## N = 1 last item, N = 30 Last 30 items.
du -h /root/test | tail -n N 

Not the answer you're looking for? Browse other questions tagged or ask your own question.