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`
        if [ -f $source ]; then
                echo "`basename $source` is a file"
        if [ -d $source ]; then 
                echo "`basename $source` is a directory"
                . Script.sh $source
  • 1
    Add -mindepth 1 to your find. But follow DepressedDaniel's excellent advice
    – xhienne
    Commented Mar 23, 2017 at 0:32

1 Answer 1


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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .