Search code examples
linuxfileubuntuterminaldirectory

How do I find the sum of sizes of all files in a directory?


I'm currently using Ubuntu 20.04. How do I find the total size of all files in a directory? Accuracy is important here. I was previously using:

du -b

However, upon checking, it was giving me a value that is larger than the sum of all file sizes in the folder. Is there a different command I can use?


Solution

  • ( find . -maxdepth 1 -type f -exec stat -c%s {} + \
      | tr '\n' + 
      echo 0
    ) | bc
    
    • find with -maxdepth 1 doesn't descent into subdirectories. -type f only lists files. -exec runs the command for all the files, stat -c%s shows the size of each file.
    • tr replaces each newline with a +
    • echo 0 puts a 0 at the end so there's no trailing +
    • bc works as a calculator, it outputs the sum