sum all numbers from "du"
In AWK:
{ sum += $1 }
END { print sum }
So
du -b /tmp/* | awk '{ sum += $1 } END { print sum }'
Note that the result won’t be correct if the directories under /tmp
have subdirectories themselves, because du
produces running totals on directories and their children.
du -s
will calculate the sum for you correctly (on all subdirectories and files in /tmp
, including hidden ones):
du -sb /tmp
and du -c
will calculate the sum of the listed directories and files, correctly too:
du -cb /tmp/*
You can also produce a total sum of selected files with du -c
. This works even if an argument of du
is not a directory, what is not the case of du -s
:
$ du -sb file1 file2
17 file1
18 file2
$ du -cb file1 file2
17 file1
18 file2
35 total
BTW, for interactive use I recommend adding -h
option instead of -b
or any other multiplier of block-size. This will print the size in human readable unit format.
$ du -ch file1 file2
4.0K file1
4.0K file2
8.0K total
It is simple you can use:
du -b /tmp/* | awk 'BEGIN{i=0} {i=i+$1} END{print i}'
If you are not using wildcard, if you are using directory name like /tmp
, then you need to avoid the last entry because output of du -b /tmp
is like:
size1 file1
size2 file2
size_total .
So now you should avoid this last entry, so use:
du -b /tmp | awk 'BEGIN{i=0} {if( $2 != "." ){i=i+$1}} END{print i}'
However you can also use -s
option, it will calculate the summary for you then you don't need to add the values, just print the last one, i.e.:
du -s directory