Linux 获取 指定目录 下的 最大子目录深度

命令

function getDirMaxDepth() {
    folder_name="$1"

    if [ ! -d "$folder_name" ];then
        echo "The dir(\"${folder_name}\") does not exist!"
        exit 3
    fi

    this_dir_tmp=`pwd`

    folder_name=`echo "$folder_name"|sed "s#^./#$this_dir_tmp/#g"`
    folder_name=`echo "$folder_name"|sed "s#^\([a-zA-Z]\+.*\)#$this_dir_tmp/\1#g"`

    depth_foler()
    {
        this_dir=`pwd`
        source_folder="$1"
        source_folder=`echo $source_folder |sed 's#/$##g'`
        test_folder="$2"

        cd $test_folder
        count=0
        while [ ! `pwd` = $source_folder ]
        do
            count=`expr $count + 1`
            cd ..
        done

        cd $this_dir
        return $count
    }

    target_folder="$folder_name"
    depth_max=1

    for i in `du "$target_folder"` ;do
        if [ -d $i -a ! $i = $target_folder ];then
            depth_foler "$target_folder" "$i"
            retval=$?
            echo "$i : $retval" # 打印每个子目录的深度
            if [ $depth_max -lt $retval ];then
                    depth_max=$retval
            fi
        fi

    done

    echo "max depth: $depth_max"
}

测试

getDirMaxDepth xx
posted @ 2020-01-23 01:16  schips  阅读(408)  评论(0编辑  收藏  举报