1

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

gmhk
  • 15,598
  • 27
  • 89
  • 112

3 Answers3

2

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
Perleone
  • 3,958
  • 1
  • 26
  • 26
1

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

gmhk
  • 15,598
  • 27
  • 89
  • 112
  • 1
    If you have any files (or directories) with spaces in them, change the line `for names in $(find /tmp/files/ -type f);` to `find /tmp/files/ -type f | while read names` – user000001 Feb 28 '13 at 10:35
0

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
MelBurslan
  • 2,383
  • 4
  • 18
  • 26
  • Your second answer looks good, I was able to get up to that level, if I find that as a directory, again I need to search , that part I am getting stuck Not able to find any ways to implement that, 2) one more point I find is every time I see the level of sub directories will be varying for every input, In my example I have used 4 directories after home, it may 3 levels for other input, it may be 7 levels for other input – gmhk Feb 26 '13 at 08:44