Skip to content

Instantly share code, notes, and snippets.

@susomena
Created February 3, 2016 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save susomena/46d612558e2d9394c6a3 to your computer and use it in GitHub Desktop.
Save susomena/46d612558e2d9394c6a3 to your computer and use it in GitHub Desktop.

File Size Sum Script

By Jesús Mena.

This script sums the size of all files in a directory (the current directory by default). It accepts three mutually exclusive and optional arguments, -K, -M and -G. This arguments are used to get the result in kilobytes, megabytes and gigabytes respectively. If no arguments are given the result is shown in bytes.

#!/bin/bash
function usage () {
cat <<EOF
Usage: $0 [-K|-M|-G] [DIRECTORY]
where:
-K returns result in KB
-M returns result in MB
-G returns result in GB
Sums the size of all files in a directory (the current directory by default).
EOF
exit 0
}
if [ "$1" = "--help" ]; then
usage
fi
directory=''
factor=1
unity=''
if [ $# -lt 2 ]; then
directory=$1
fi
while getopts ":KMG" opt; do
case $opt in
K) [[ -n "$unity" ]] && usage || factor=1024; directory=$2; unity='KB'; ;;
M) [[ -n "$unity" ]] && usage || factor=1048576; directory=$2; unity='MB'; ;;
G) [[ -n "$unity" ]] && usage || factor=1073741824; directory=$2; unity='GB' ;;
\?) echo "Invalid option: -$OPTARG"; usage ;;
esac
done
ls $directory -FaGl | awk -v awk_factor=$factor -v awk_unity=$unity '{ total += $4 }; END { printf("%.2f%s\n",total/awk_factor,awk_unity) }'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment