randeepsp
randeepsp

Reputation: 3842

recursive listing of directories

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/bin/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.

Upvotes: 2

Views: 1408

Answers (4)

VonC
VonC

Reputation: 1324208

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.

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 753695

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.

Upvotes: 1

too much php
too much php

Reputation: 90998

ls already has a recursive option:

ls -R

Upvotes: 3

Slartibartfast
Slartibartfast

Reputation: 1700

I suggest replacing this with:

find . -print

Upvotes: 5

Related Questions