Bash – Sum of filesize of a list of files

awkbashfiles

I have a text-file that contains a list of filenames (one filename per line).

Now I would like to calculate the size of all these files. I think I will have to do a ls -la on every line of the file and then accumulate the filesize.

I think that awk will be part of the solution, but thats just guess.

Best Answer

With GNU stat:

stat -c %s -- $(<list) | paste -d+ -s - | bc
  • stat displays information about the file
    • -c specifies the format, %s gives the filesize in bytes
  • paste -d+ -s concats the output together line by line with a + as delimiter
  • bc piped to bc, it will be calculated together.

Add a -L option to stat, if for symlinks, you'd rather count the size of the file that the symlink eventually resolves to.

That assumes a shell like ksh, bash or zsh with the $(<file) operator to invoke split+glob on the content of a file.

Here list is expected to be a space, tab or newline (assuming the default value of $IFS) delimited list of file patterns (as in *.txt /bin/*). For a list of file paths, one per line, you'd need to disable globbing and limit $IFS to newline only, or with GNU xargs:

xargs -rd '\n' -a list stat -c %s -- | paste -sd+ - | bc
Related Question