shell脚本中的递归问题

时间:2013-04-02 09:21:49

标签: linux bash shell sh

function syncfile(){
                echo "[ DONE $file ]"
        return ;
}
function syncfolder(){

        folder=$1
        for foo in `ls -1 $folder`
        do

                file="$folder/$foo"

                        if [ -d $file ];then
                                syncfolder $file
                        elif [ -e $file ];then
                                syncfile $file
                        else
                                echo "$file is neither file nor directory"
                        fi
        done
        return;
}

以上是我的两个递归函数..当我调用syncfolder $foldername时,它在以下情况下没有给出正确的输出..

假设层次结构如下

portchanges/
portchanges/script/script1/script1.sh
portchanges/script/script1/script2.sh
portchanges/script/script1/script3.sh

portchanges/script/script4.sh
portchanges/script/script5.sh

portchanges/script6.sh
portchanges/script7.sh

portchanges/appl/script11/script11.sh
portchanges/appl/script11/script12.sh
portchanges/appl/script11/script13.sh

现在如果foldername=portchanges 我打电话给syncfolder $foldername

仅针对

进行处理
portchanges/script/script1/script1.sh
portchanges/script/script1/script2.sh
portchanges/script/script1/script3.sh

使用function syncfile()函数调用...然后转到return函数的syncfolder

它将在script6.sh目录中搜索script7.shportchanges/script/script1/ !!这是完全不正当的行为!!

我应该怎么做呢?它会递归处理整个文件夹,并且每个文件都会转到syncfile()函数?

2 个答案:

答案 0 :(得分:5)

folder变量声明为local。您不希望递归调用更改调用者变量的值。

答案 1 :(得分:0)

以下是我的情况。如果要打印目录名,请将其传递给syncfile。

function syncfolder(){
        syncfile $1
        local folder=$1
        for foo in `ls -1 $folder`
        do

                file="$folder/$foo"

                        if [ -d $file ];then
                                syncfolder $file
                        elif [ -e $file ];then
                                syncfile $file
                        else
                                echo "$file is neither file nor directory"
                        fi
        done
        return;
}