Batch rename files with Mac Bash,while the dir index should be recorded
Limit globbing to directories only by appending a slash:  for dir in */

If you cd into subdirectories, you don't need to construct a new path for each file.  If you cd inside a subshell with ( cd … ), the original directory will be restored when subshell exits.  Make sure to increment n outside of the subshell, or the new value will be lost!

The IFS= is not needed; bash will split the filenames properly.  You just need to quote the variable when you refer to it.

n=0
for d in */ ; do
    ( cd "$d" &amp;&amp; for f in * ; do mv  "$f" $n"_$f" ; done )
    (( n++ ))
done