Jatin Bodarya
Jatin Bodarya

Reputation: 1455

recursion issue in shell script

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;
}

above are my two functions for recursions.. when I call syncfolder $foldername it is not giving proper output in following case ..

suppose hierarchy is like below

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

now if foldername=portchanges and I call syncfolder $foldername

It process only for

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

with function syncfile() function call...and then it goes to return of syncfolder function.

it is going to search script6.sh and script7.sh in portchanges/script/script1/ directory !! which is totally improper behavior !!

What should I do so It process recursively for entire folder and for every file goes to syncfile() function ?

Upvotes: 0

Views: 166

Answers (2)

Dipto
Dipto

Reputation: 2738

The following is working in my case. if you want to print the directory name, pass it to 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;
}

Upvotes: 0

choroba
choroba

Reputation: 241868

Declare the folder variable as local. You do not want the recursive call to change the value of the caller's variables.

Upvotes: 5

Related Questions