10.5. Total Bytes in the Current Directory

If you want to know how much space the contents of the current directory take up, you can use something like the following:

let TotalBytes=0

for Bytes in $(ls -l | grep "^-" | awk '{ print $5 }')
   let TotalBytes=$TotalBytes+$Bytes

# The if...fi's give a more specific output in byte, kilobyte, megabyte, 
# and gigabyte

if [ $TotalBytes -lt 1024 ]; then
   TotalSize=$(echo -e "scale=3 \n$TotalBytes \nquit" | bc)
elif [ $TotalBytes -lt 1048576 ]; then
   TotalSize=$(echo -e "scale=3 \n$TotalBytes/1024 \nquit" | bc)
elif [ $TotalBytes -lt 1073741824 ]; then
   TotalSize=$(echo -e "scale=3 \n$TotalBytes/1048576 \nquit" | bc)
   TotalSize=$(echo -e "scale=3 \n$TotalBytes/1073741824 \nquit" | bc)

echo -n "${TotalSize}${suffix}"

Code courtesy of me, Sam Schmit, and Sam's uncle Jean-Paul, who ironed out a fairly major bug in my original code, and just generally cleaned it up.

The lsbytesum script code seen earlier is actually a later revision of this written in awk instead of bash. It's a bit faster.

Note that you could also just use ls -l | grep ^total | awk '{ print $2 }' because ls -l prints out a line at the beginning that is the approximate size of the directory in kilobytes - although for reasons unknown to me, it seems to be less accurate (but obviously faster) than the above script.

Relative speed: this version takes about 0.32 seconds in /usr/bin/ (about 1660 files in the directory) on an unloaded 800 MHz Celeron.