berserkBASH
berserkBASH

Reputation: 3

Bash - How to output files from subdirectories with nest level

I have code, which output files and directories from directory and subdirectories. But I should to output only files with nest level. Also I can't use find and ls. Only recursion with for loop. How to do it?

#!/bin/bash

recurse() {
 for i in "$1"/*;do
    if [ -d "$i" ];then
        recurse "$i"
    elif [ -f "$i" ]; then
        echo "level) $i"
    fi
 done
}

recurse "$1"

Call ./script.sh /home

Upvotes: 0

Views: 40

Answers (1)

declension
declension

Reputation: 4185

You're almost there! Assuming you meant a zero-based nest level, try this:

#!/usr/bin/env bash
set -e -u

recurse() {
  local level="${2:-0}"
  for i in "$1"/*; do
    if [ -d "$i" ]; then
      recurse "$i" "$(( level + 1 ))"
    elif [ -f "$i" ]; then
      echo "level $level) $i"
    fi
  done
}

recurse "$1"

Note this is passing through a state variable (depth here), which is common in recursive programming. The default is set to zero.

To test for a tree like this:

$ tree
.
├── bar
├── foo
│   ├── bar
│   │   ├── hello
│   │   └── hi
│   └── me
└── script.sh

It runs like this:

$ ./script.sh .
level 2) ./foo/bar/hi
level 1) ./foo/me
level 0) ./script.sh

Upvotes: 1

Related Questions