开发者

recursive listing of directories

开发者 https://www.devze.com 2023-01-23 18:48 出处:网络
I have the below code which has to do a recursive listing of all the files and directories. I am not sure if it is working fine.

I have the below code which has to do a recursive listing of all the files and directories. I am not sure if it is working fine.

#!/usr/b开发者_如何学JAVAin/sh
recur_fun()
{
    for i in `ls -ltr | awk '{print $9}'` 
    do
        echo $i;
        cd $i;
        ls
        pwd
        recur_fun
        cd ..
        pwd
    done
} 

recur_fun

I need to copy the name of the file and then use it in clearcase.


I suggest replacing this with:

find . -print


ls already has a recursive option:

ls -R


Note: I would rather recommend going with cleartool command than OS-specific shell commands.

For instance:

cleartool ls -r -nxn

would list all files recursively, private or not.
See Command line to delete all ClearCase view-private files for more.


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:

  1. It won't handle names with spaces in them.
  2. When something isn't a directory, the cd will at best produce an error message.
  3. At worst, if CDPATH is set and the name can be found on CDPATH, then the script is going to go haywire.
  4. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消