Ivan Ivanov
Ivan Ivanov

Reputation: 61

Recursively search for files

I am trying to find all files by passing a directory name in all sub directories meaning the process is recursive here is my code

myrecursive() {
  if [ -f $1 ]; then 
    echo $1
  elif [ -d $1 ]; then
    for i in $(ls $1); do
      if [ -f $1 ]; then
        echo $i 
      else
        myrecursive $i
      fi
    done
  else
    echo " sorry"
  fi
}
myrecursive $1

However when I pass directory with another directory I get 2 times sorry,where is my mistake?

Upvotes: 3

Views: 1412

Answers (3)

tso
tso

Reputation: 4924

#!/bin/bash
myrecursive() {
  if [ -f "$1" ]; then 
    echo "$1"
  elif [ -d "$1" ]; then
    for i in "$1"/*; do
      if [ -f "$i" ]; then #here now our file is $i
        echo "$i"
      else
        myrecursive "$i"
      fi
    done
  else
    echo " sorry"
  fi
}
myrecursive "$1"

Upvotes: 0

Dave
Dave

Reputation: 3623

The problem with your code is quite simple.

The ls command will return a list of filenames, but they aren't valid for recursion. Use globbing instead. The loop below simply replaces $(ls) with $1/*

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

Hope that helps

Upvotes: 0

Andrii Abramov
Andrii Abramov

Reputation: 10751

The goal that you are trying to achieve could be simply done by using find command:

# will search for all files recursively in current directory 
find . * -exec echo {} \;

# will search for all *.txt file recursively in current directory 
find . -name "*.txt" -exec echo {} \;

# will search for all *.txt file recursively in current directory 
# but depth is limited to 3
find . -name "*.txt" -max-depth 3 -exec echo {} \;

See man find for manual. How to run find -exec?

Upvotes: 2

Related Questions