递归搜索文件

3

我正在尝试通过传递一个目录名来查找所有子目录中的文件,这意味着该过程是递归的。以下是我的代码:

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

然而,当我传递一个目录和另一个目录时,我会得到两次抱歉的提示,我的错误在哪里?

4
为什么不直接使用查找命令? - Raman Sailopal
我正在尝试自己实现它,我知道find可以完成这项工作,但这不是重点。 - Ivan Ivanov
3个回答

2
你可以使用 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 find如何运行 find -exec 命令?


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

希望这有所帮助。

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"

需要在变量周围加上双引号。 - codeforester

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接