gmhk
gmhk

Reputation: 15960

Traverse a directory structure using a for loop in shell scripting

I am looking to traverse a directory using a conditional for / while Loop

Scenario : path is /home/ABCD/apple/ball/car/divider.txt

Say I always start my program from /home I need to iterate from home -- > ABCD --> apple --> ball --> car --> divider.txt

Every time I iterate, check if the obtained path is a directory or a file, if file exit the loop and return me the path if the returned path is directory, loop one more round and continue..

Updated question

FILES="home"
for f in $FILES
do

    echo "Processing $f"  >> "I get ABCD as output
        if[-d $f]
  --> returns true, in my next loop, I should get the output as /home/ABCD/apple..
        else 
          Break;
        fi

done

after I exit the for loop, I should have the /home/ABCD/apple/ball/car/ as output

Upvotes: 1

Views: 6960

Answers (3)

gmhk
gmhk

Reputation: 15960

This is the way I have implemented to get it working

for names in $(find /tmp/files/ -type f); 
do
    echo " ${directoryName} -- Directory Name found after find command : names" 

    <== Do your Processing here  ==>

done

Names will have each file with the complete folder level

/tmp/files is the folder under which I am finding the files

Upvotes: 1

Perleone
Perleone

Reputation: 4038

Besides the multi-purpose find you might also want to take a look at tree. It will list contents of directories in a tree-like format.

$ tree -F /home/ABCD/
/home/ABCD/
`-- apple/
    `-- ball/
        `-- car/
            `-- divider.txt

3 directories, 1 file

Upvotes: 2

MelBurslan
MelBurslan

Reputation: 2511

find /home -type d

will give you all the directories under /home and nothing else. replace /home with the directory of your choice and you will get directories under that level.

if your heart is set on checking every file one by one, the if..then test condition you are looking for is :

if [ -f $FILE ]
then
echo "this is a regular file"
else 
echo "this is not a regular file, but it might be a special file, a pipe etc."
fi

-or-

if [ -d $FILE ]
then
echo "this is a directory. Your search should go further"
else 
echo "this is a file and buck stops here"
fi

Upvotes: 0

Related Questions