Skip to content

Instantly share code, notes, and snippets.

@molotovbliss
Created June 15, 2019 02:07
Show Gist options
  • Save molotovbliss/9c2f4c864afb9547b7cf4d6c665a0284 to your computer and use it in GitHub Desktop.
Save molotovbliss/9c2f4c864afb9547b7cf4d6c665a0284 to your computer and use it in GitHub Desktop.
Basic treesize bash script with du & better defaults
#/bin/sh
#set -x #echo on
if [ "$1" == "-h" ]; then
echo "usage: treesize [depth (0)] [sizelimit (1MB)]"
echo ""
echo "example: treesize 3 20G"
echo ""
echo "Show all folders larger than 20GBs & only scan 3 directories in deep"
echo "defaults are 0 depth, 1MB limit equiv to treesize 0 1MB"
exit
fi
if [ "$1" == "" ]; then
DEPTH="-d0"
else
DEPTH="-d$1"
fi
if [ "$2" == "" ]; then
SIZE="-t1MB"
else
SIZE="-t$2"
fi
du -hx $SIZE $DEPTH * | sort -h;
@bliotti
Copy link

bliotti commented Jan 2, 2025

POSIX-compliant /bin/sh

#!/bin/sh
#set -x #echo on

if [ "$1" = "-h" ]; then
    echo "usage: treesize [depth (0)] [sizelimit (1MB)]"
    echo ""
    echo "example: treesize 3 20G"
    echo ""
    echo "Show all folders larger than 20GBs & only scan 3 directories deep"
    echo "defaults are 0 depth, 1MB limit equivalent to treesize 0 1MB"
    exit
fi

if [ -z "$1" ]; then
    DEPTH=""
else
    DEPTH="--max-depth=$1"
fi

if [ -z "$2" ]; then
    SIZE="1M"
else
    SIZE="$2"
fi

# Use find to filter by size since du lacks flexible size filters
du -h $DEPTH | awk -v size="$SIZE" '
    function parse_size(s) {
        n = substr(s, 1, length(s)-1);
        unit = substr(s, length(s));
        if (unit == "G") return n * 1024 * 1024 * 1024;
        if (unit == "M") return n * 1024 * 1024;
        if (unit == "K") return n * 1024;
        return n;
    }
    BEGIN { size_bytes = parse_size(size); }
    { if (parse_size($1) >= size_bytes) print; }
' | sort -h

@molotovbliss
Copy link
Author

@bliotti thanks for this edit, much appreciated! 🤠👍🏻

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment