#!/usr/bin/env bash
help_text="
NAME
lf - A script to recursively list folders and show folder details.
USAGE
lf [options] <directory (. for current directory)>
OPTIONS
-m|maxdepth <number>
Max directory depth.
-t|--filetypecount
Show a count of files by file type.
-h|--help
Show help text.
DESCRIPTION
A script to recursively list folders, show folder details (size and number of files) and
optionally a count of files by file size.
AUTHOR
mjnurse.github.io - 2020
"
help_line="A script to recursively list folders and show folder details"
web_desc_line="A script to recursively list folders and show folder details"
try="Try ${0##*/} -h for more information"
tmp="${help_text##*USAGE}"
usage="${tmp%%OPTIONS*}"
file_type_count_yn=n
max_depth=99
while [[ "$1" != "" ]]; do
case $1 in
-h|--help)
echo "$help_text"
exit
;;
-m|--maxdepth)
shift
(( max_depth=${1}*3 ))
;;
-t|--filetypecount)
file_type_count_yn=y
;;
*)
break
;;
esac
shift
done
if [[ "$1" == "" ]]; then
# xargs strips the whitespace and replaces multiple spaces with one.
echo "Usage: $usage" | xargs
echo "${try}"
exit 1
fi
gre="\e[92m"
cya="\e[96m"
mag="\e[95m"
whi="\e[39m"
ind="| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | "
function f() {
if [[ "$1" != "" ]]; then
curr_dir="${1:0:-1}"
fi
depth="$2"
indent=$(( depth * 2 - 2 ))
file_count=$(find "$curr_dir" -maxdepth 1 -type f | wc -l)
size="$(du "$curr_dir" -d0 -h)"
size="${size%%/*}"
if [[ $file_type_count_yn == y ]]; then
list="($(find "$curr_dir" -maxdepth 1 -type f \
| sed 's/^[^\.]*$/other/; s/.*\.//' \
| sort | uniq -c | tr -d '\n' \
| sed 's/ */, /g; s/^, *//'))"
else
list=""
fi
if [[ $indent -ge 0 ]]; then
ind_str="${ind:0:$indent}|_"
else
ind_str=""
fi
echo -e "${ind_str}${curr_dir##*/}${gre} - ${file_count} files ${cya}${size} ${mag}${list}${whi}" | sed 's/[\t ][\t ]*/ /g'
if [[ $depth -lt $max_depth ]]; then
for d in "${curr_dir}"/*/; do
if [[ ! -d "$d" ]]; then
continue
fi
(( depth=depth+1 ))
f "$d" $depth
(( depth=depth-1 ))
done
fi
}
if [[ "${1:0:1}" == "/" ]]; then
dir="$1"
else
dir="$(pwd)/$1"
fi
echo "dir:$dir:"
cd "$dir" || exit 1
f "$(pwd)/" 0