amazinghorse24
amazinghorse24

Reputation: 59

bash script: Loop through a directory

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!

Upvotes: 2

Views: 1272

Answers (4)

Gordon Davisson
Gordon Davisson

Reputation: 126038

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"

Upvotes: 2

Dave L
Dave L

Reputation: 984

'find . -type d' does this

Upvotes: 0

Dave
Dave

Reputation: 14198

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

For example: find -ls

Upvotes: 0

Amir Afghani
Amir Afghani

Reputation: 38561

function fnd {

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

}

Upvotes: 1

Related Questions