11.4. 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 }')
do
let TotalBytes=$TotalBytes+$Bytes
done
# 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)
suffix="b"
elif [ $TotalBytes -lt 1048576 ]; then
TotalSize=$(echo -e "scale=3 \n$TotalBytes/1024 \nquit" | bc)
suffix="kb"
elif [ $TotalBytes -lt 1073741824 ]; then
TotalSize=$(echo -e "scale=3 \n$TotalBytes/1048576 \nquit" | bc)
suffix="Mb"
else
TotalSize=$(echo -e "scale=3 \n$TotalBytes/1073741824 \nquit" | bc)
suffix="Gb"
fi
echo -n "${TotalSize}${suffix}"
|
Code courtesy of me, Sam Schmit (<id at pt dot lu>), and
Sam's uncle Jean-Paul, who ironed out a fairly major bug in my original
code, and just generally cleaned it up.
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 process takes between 3.2 and 5.8 seconds in /usr/bin/
(14.7 meg in the directory) on an unloaded 486SX25, depending on how much
of the information is cached (if you use this in a prompt, more or less of
it will be cached depending how long you work in the directory).