Skip to content

Instantly share code, notes, and snippets.

@fullpipe
Last active January 30, 2018 10:36
Show Gist options
  • Save fullpipe/41fb93c6145cf412ce084a696e27a471 to your computer and use it in GitHub Desktop.
Save fullpipe/41fb93c6145cf412ce084a696e27a471 to your computer and use it in GitHub Desktop.
Calculate size of a source code base
#!/bin/bash
#
# Copyright 2016-2017 by Chris Niswander.
#
# Example script calculates the total size (in bytes) of the files
# having (a) specified type(s)/extension(s),
# in the directory tree specified by command line argument.
#
# See also: http://bitboost.com/python-obfuscator/articles_and_resources/how-to-calculate-the-total-size-length-of-your-code-or-codebase-in-bytes-fixing-inaccuracies-problems-in-du--an-easy-way
#
# The --exclude option can be used multiple times in the same command line
# to exclude multiple file types.
# e.g. $ du --apparent-size -ac -b delme --exclude=*.txt --exclude=*.ps
#
# These 'excluded' file types
# will be the only types we actually count the size of,
# when we run du twice and subtract one result from the other.
du_flags_excluding=" --exclude=*.py --exclude=*.js --exclude=*.ts --exclude=*.scss --exclude=*.php "
#
echo "measuring size of code in directory structure:" "$1"
echo "file type(s)/extension(s) measured are those 'excluded' from 2nd measurement:" $du_flags_excluding
dirpath="$1"
du_flags=" --apparent-size -b -ca "
#
# Total the bytes for all files and directories in argument directory:
read -a du_result_inclusive < <(du $du_flags $dirpath | tail -n 1)
#
# Total the bytes for all files and directories in argument directory,
# *except* the file type(s) specified by $du_flags_excluding:
read -a du_result_excluding < <(du $du_flags $du_flags_excluding $dirpath | tail -n 1)
#
echo "du result inclusive:" $du_result_inclusive
echo "du result excluding specified file type/extension:" $du_result_excluding
#
# Subtract to get the total size (in bytes) of the file type(s) of interest.
echo $((du_result_inclusive - du_result_excluding))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment