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.
(cd -- "$d" && rFunc)performs thecdin subshell and the parent call's current directory is unchanged, whereas your versioncd's into$dbut doesn't back out of it afterrFuncreturns.To fix yours you should put the subshell back in, or go back up to the parent directory explicitly, e.g. with:
or: