Bash Prompt HOWTO: $Revision: 0.100 $, $Date: 2009/08/07 02:33:22 $ | ||
---|---|---|
Prev | Chapter 10. Prompt Code Snippets | Next |
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="KiB" elif [ $TotalBytes -lt 1073741824 ]; then TotalSize=$(echo -e "scale=3 \n$TotalBytes/1048576 \nquit" | bc) suffix="MiB" else TotalSize=$(echo -e "scale=3 \n$TotalBytes/1073741824 \nquit" | bc) suffix="GiB" fi 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.