Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does recursive function go though only one sub directory

I have found the answer to get my code to work but I want to know why it works and my code doesn’t

rFunc() {
  for d in *; do
    if [ -d "$d" ]; then
      cd "$d"
      rFunc
    fi
    #Do Something
  done
}

This code will go though only one sub directory but if I use the code from this answer it goes though all sub directories. Why?

(cd -- "$d" && rFunc)

Also, what is the purpose of the --? My code works without it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

(cd -- "$d" && rFunc) performs the cd in subshell and the parent call’s current directory is unchanged, whereas your version cd‘s into $d but doesn’t back out of it after rFunc returns.

To fix yours you should put the subshell back in, or go back up to the parent directory explicitly, e.g. with:

cd "$d"
rFunc
cd ..

or:

pushd "$d"
rFunc
popd
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading