3

I am trying to make a script that will list all files and directories in a given directory. I want to make this script to call itself, in the end showing all files and directories. I know that you can easily do that with find, but I want to practice recursive scripts, and I don't know why my recursive given parameter is not what I was expecting, it's value doesn't change.

for source in `find $1 -maxdepth 1 -type d,f`
do
        if [ -f $source ]; then
                echo "`basename $source` is a file"
        fi
        if [ -d $source ]; then 
                echo "`basename $source` is a directory"
                . Script.sh $source
        fi
done
  • 1
    Add -mindepth 1 to your find. But follow DepressedDaniel's excellent advice – xhienne Mar 23 '17 at 0:32
3

The following line is the culprit:

. Script.sh $source

While you could conceivably do recursion that way, it makes it hard to reason about because the variables changed by the next level of recursion are changed in the caller as well. Probably you just want to invoke it without sourcing it:

Script.sh $source

Or, better yet:

"$0" "$source"

Reliably getting the source script in all cases is a bit tricky, though. Much better yet is to use functions to do recursion (in Bash):

function f()
{
   ...
   f different_args
   ...
}

And declare any variables used within f as local so they won't be mutated by the recursive call to f.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.