Search code examples
bashawkfinddirectory-structure

A better way of getting sizes of subdirectories


I was trying to figure out the sizes of some subdirectories in a shared folder, and was wondering if there is a 'one-liner' out there that can do this (for all of you crazy awk guys)...

The one hiccup with my situation is that I might not have permissions to some of the subfolders, so the directory size is going to be a best-effort, as we may get a 'permission denied' response to a recursive command.

Here is what I came up with:

#!/bin/bash
DIR=/my/shared/folder/*

for d in $DIR
do
    if [ -d $d ]
    then
        dirsize=$(du -sh $d 2>/dev/null | cut -f1)
        echo "$dirsize - $d"
    fi
done

The 2>/dev/null is important because of the permissions issue that may arise, so we don't want to see errors. I also want to see the entire path, which is why

Anyone know of a more creative way of doing this? I imagine that find, combined with awk in some capacity could generate the one liner needed to accomplish this.


Solution

  • If what you need is the full path then you can do

    du -hs /my/shared/folder/*/
    

    If you want to supress errors from your output:

    du -hs /my/shared/folder/*/ 2>/dev/null
    

    And as pointed out by Socowi, if you want the output to be separated by a dash instead of a tab you can manipulate it with sed:

    du -hs /my/shared/folder/*/ 2>/dev/null | sed 's/\t/ - /'