Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Recursion is not working properly

Status
Not open for further replies.

TipGiver

Programmer
Sep 1, 2005
1,863
Hello.
Firstly, let me tell you want i want to do. I give a folder (directory -d) as an argument ($1), and i want to know what is the most recent file in every folder. The $1 folder may have many folders inside and files, the sub-folders can have other sub folders and other files, and so on.
So a recursive function is needed.

In the For Loop i check if the 'file' is a folder with the '-d'. The recursion is done in the IF statement. If it is not a directory then i assign the $file to a variable (since is is not a directory) called 'recent'. Then i check all items in the current folder. If the anyfile is a simple file AND it is newer than the previous assigned "recent" then the anyfile is now the recent one.

After the "done" it is supposed to have found the most recent file in the directory, but no!

Here is the code. What is/are wrong ?!
Thanks in advance.

Code:
#!/bin/bash

folder=$1
    function func1
    {
      for file in * ; do
        if [ -d $file ] ; then
          cd $file
          func1    # calls itseft
          cd ..
        else
          recent=$file
          for anyfile in * ; do
            if [ -f $anyfile ] && [ $anyfile -nt $recent ] ; then
              recent=$anyfile
            fi
          done
          # *******
          # Handle the most recent (-nt) file of the $file directory
          # *******
        fi
      done
    }
cd $folder
func1
exit -0
 
How are you returning the result to the calling script, whether it be the original caller, or func1 itself?

Annihilannic.
 
Hi

I would start again, using [tt]find[/tt] :
Code:
find . -type d [teal]|[/teal] [teal]\[/teal]
[b]while[/b] [COLOR=chocolate]read[/color] d[teal];[/teal] [b]do[/b]
  find [green][i]"$d"[/i][/green] -type f -maxdepth 1 -printf [green][i]'%Ts[/i][/green][lime][i]\t[/i][/lime][green][i]%p[/i][/green][lime][i]\n[/i][/lime][green][i]'[/i][/green] [teal]|[/teal] [teal]\[/teal]
  sort -n -r [teal]|[/teal] [teal]\[/teal]
  head -[purple]1[/purple] [teal]|[/teal] [teal]\[/teal]
  cut -f [purple]2[/purple]-
[b]done[/b]
Tested with GNU [tt]find[/tt].

Feherke.
 
Hello Annihilannic and Feherke,

Oh my God. I just saw a huge mistake. The "Handle the most recent (-nt) file of the $file directory" code should be after the last "done" just before the function ends
I was working very very late yesterday and i didnt spot this!

I'll see how this is goind to work right know, and then i'll test your code Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top