Newbie: Recursive deletion of files and dir

F

FredrikC

Hi!
I'm designing (newbie level) a script to clean up empty directories and
old files recursivly. Something is wrong..works fine when not actually
deleting anything, but when I start removing files and directories it
ends prematurly.. any heklp available..?

def thisDir(dirname,f)
Dir.chdir(dirname)
currDir=Dir.getwd
nf=0
nd=0
fs=0.0

if Dir.entries(currDir).size>2 then
Dir.foreach(currDir) {|x|
if FileTest.file?(x) && (Time.now-File.mtime(x))/(60*60*24)>15 then
f.puts("deleting file"+x)
nf=nf+1
fs=fs+File.stat(x).size
end
if FileTest.directory?(x) && x!="." && x!=".." then
lV=thisDir(x,f)
nf=nf+lV[0]
nd=nd+lV[1]
fs=fs+lV[2]
end
}
Dir.chdir("..")
end
if Dir.entries(currDir).size<=2 then
Dir.chdir("..")
f.puts("deleteting this directory:"+currDir)
nd=nd+1
#Dir.delete(currDir)
end

#Dir.chdir("..")
return [nf,nd,fs]
end
outFileName="cleaned-"+Date.today.to_s+".log"
f=File.new(outFileName,"w")
values=thisDir("./",f)
puts "Deleted "+values[0].to_s+" files"
puts "Deleted "+values[1].to_s+" directories"
puts "Total size deleted:"+(values[2]/(1024)).to_s+" kB"

Any advice is appriciated
 
E

Eero Saynatkari

FredrikC said:
Hi!
I'm designing (newbie level) a script to clean up empty directories and
old files recursivly. Something is wrong..works fine when not actually
deleting anything, but when I start removing files and directories it
ends prematurly.. any heklp available..?

def thisDir(dirname,f)
Dir.chdir(dirname)
currDir=Dir.getwd
nf=0
nd=0
fs=0.0

if Dir.entries(currDir).size>2 then
Dir.foreach(currDir) {|x|
if FileTest.file?(x) && (Time.now-File.mtime(x))/(60*60*24)>15 then
f.puts("deleting file"+x)
nf=nf+1
fs=fs+File.stat(x).size
end
if FileTest.directory?(x) && x!="." && x!=".." then
lV=thisDir(x,f)
nf=nf+lV[0]
nd=nd+lV[1]
fs=fs+lV[2]
end
}
Dir.chdir("..")
end
if Dir.entries(currDir).size<=2 then
Dir.chdir("..")
f.puts("deleteting this directory:"+currDir)
nd=nd+1
#Dir.delete(currDir)
end

#Dir.chdir("..")
return [nf,nd,fs]
end
outFileName="cleaned-"+Date.today.to_s+".log"
f=File.new(outFileName,"w")
values=thisDir("./",f)
puts "Deleted "+values[0].to_s+" files"
puts "Deleted "+values[1].to_s+" directories"
puts "Total size deleted:"+(values[2]/(1024)).to_s+" kB"

Any advice is appriciated

I did not read this code yet but take a look at ri FileUtils,
it has useful methods including two that might be handy here:

FileUtils.rm_rf
FileUtils.mkdir_p


E
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,816
Latest member
SapanaCarpetStudio

Latest Threads

Top