2

I am currently trying to take a directory as a parameter, then list the contents of the directory. If another directory is within that directory then do the same recursively.

Current Code:

#! /bin/bash

function gothrudir {
for f in $1
do 
if [ -n "$( file $f|grep "directory" )" ] ;
then
gothrudir $f
else
ls $f
fi
done
]
gothrudir $1
gothrudir `pwd`

I am unsure about how to pass all the files in the directory to be looped through. Currently it is just an endless loop because it only examines the given directory, sees its a directory, then recalls itself.

Thanks for your help!

4 Answers 4

2

As others have pointed out, find is a much better way to do this. But just for completeness, here's how to fix your recursive bash function. There are three things I changed (plus some minor formatting changes): use "$1"/* to get a list of files in $1, double-quote all paths (they sometimes contain spaces), and use [ -d ... ] rather than calling file to see if something is a directory.

function gothrudir {
    for f in "$1"/*; do
        if [ -d "$f" ]; then
            gothrudir "$f"
        else
            ls "$f"
        fi
    done
}

gothrudir "$1"
Sign up to request clarification or add additional context in comments.

1 Comment

hey man just wanted to say thanks for your tip, I found what I needed -- I have a bash script that has to sift through directories and add/remove at times, was driving me crazy, but the double quoted loop variable "$f" fixed it, thanks so much, your completeness saved me a lot of hassle!! :D
1
function fnd {

    find $1 -type d -exec ls -d {} \; 

}

1 Comment

Thanks for you help. I took out the -d on ls to show all the contents.
0

Is there a reason you are doing this rather than using find?

For example: find -ls

1 Comment

Yup, just facepalm'd at this. Sorry I am just starting out with Bash/Linux.
0

'find . -type d' does this

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.