5

We want to calculate the first numbers that we get from du

du -b /tmp/*
6       /tmp/216c6f99-6671-4865-b8bc-7205f5388752_resources
668669  /tmp/hadoop7887078727316788325.tmp
6       /tmp/hadoop-hdfs
42456   /tmp/hive
32786   /tmp/hsperfdata_hdfs
6       /tmp/hsperfdata_hive
32786   /tmp/hsperfdata_root
262244  /tmp/hsperfdata_yarn

so final sum will be

sum=6+668669+6+42456+32786+6+32786+262244


echo $sum

How we can do it by awk or perl one liners?

15

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/*
4

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
  • 1
    variables initialize to zero, if you'd like to golf some bytes off :) – Jeff Schaller Feb 28 at 17:57
2

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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