递归搜索文件

时间:2017-05-28 14:07:41

标签: bash shell recursion

我试图通过在所有子目录中传递目录名来查找所有文件,这意味着进程是递归的,这是我的代码

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

然而,当我用另一个目录传递目录时,我得到2次抱歉,我的错误在哪里?

3 个答案:

答案 0 :(得分:0)

您尝试实现的目标可以通过使用find命令完成:

# 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 {} \;

有关手册,请参阅man findHow to run find -exec?

答案 1 :(得分:0)

您的代码问题非常简单。

ls命令将返回文件名列表,但它们不适用于 递归。请改用globbing。下面的循环只是将$(ls)替换为$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

希望有所帮助

答案 2 :(得分:0)

#!/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"