Just pass current depth as a parameter:
function tree(){
local max_depth=$2
if [ -n "$max_depth" ]; then
max_depth=3
fi
tree_helper $1 0 $max_depth
}
function tree_helper() {
local current_depth=$2
local max_depth=$3
for path in "{$1}/*"
if [ -d "$path"]; then
printf "%5s %s %d" DIR $path $current_depth #and also depth
if [ $current_depth -lt $max_depth ]; then
tree_helper "$path" $((current_depth+1)) $max_depth
fi
else [ -f "$path"]; then
printf "%5s %s" File $path $current_depth
fi
done
}
You can also use find
with -maxdepth
option:
Write a file print_depth.sh
which contains:
input=$1
slashes=$(echo $input | awk -F/ '{print NF}')
echo $input $((slashes-1))
Then simply do:
chmod +x print_depth.sh
find . -maxdepth 3 -exec ./print_depth.sh {} \;