If the purpose is to get the job done, then use pre-built tools such as 'find
' or 'ls -R
' to do the job reliably.
Assuming that the purpose is to learn about recursion and shell scripting, rather than to get the job done, then it is not working fine for a number of reasons:
- It won't handle names with spaces in them.
- When something isn't a directory, the
cd
will at best produce an error message.
- At worst, if CDPATH is set and the name can be found on CDPATH, then the script is going to go haywire.
- Because you don't check that the
cd
works, you're apt to see the same files listed over, and over, and over again (once per file in a given directory).
Additionally, the two semi-colons are superfluous.
If you do need to use cd
in a script, it is usually a good idea to do that in sub-shell:
if [ -d $i ]
then ( cd $; pwd; recur_fun )
fi
When the sub-shell completes, you know the parent is still in exactly the same place it was in before - it doesn't depend on the vagaries of what the cd
command does across symlinks. Modern shells (meaning bash
) seem to think that you should normally want a 'logical cd
' operation, which bugs the hell out of me because I almost never do want that behaviour.