2017-05-28 107 views
1

我想在所有子目录意味着过程传递一个目录名找到所有文件是递归这里是我的代码递归搜索文件

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次抱歉,我的错误在哪里?

+4

为什么不利用find命令? –

+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?

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" 
+0

需要变量周围的双引号。 – codeforester