Calculate sum of several sizes of files in Bash
Use stat
instead of du
:
#!/bin/bash
for i in `grep -v ^# ~/cache_temp | grep -v "dovecot.index.cache"`; do
[ -f "$i" ] && totalsize=$[totalsize + $(stat -c "%s" "$i")]
done
echo totalsize: $totalsize bytes
According to du(1), there is a -c option whose purpose is to produce the grand total.
% du -chs * /etc/passwd
92K ABOUT-NLS
196K NEWS
12K README
48K THANKS
8,0K TODO
4,0K /etc/passwd
360K total
If you need to use the file this snippet is hopefully efficient.
xargs -a cache_file stat --format="%s" | paste -sd+ | bc -l
The xargs
is to prevent overflowing the argument limit but getting the max number of files into one invocation of stat
each time.