Dhinesh
Dhinesh

Reputation: 291

How to delete a non-empty directory using the Dir class?

Dir.delete("/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh")  

causes this error:

Directory not empty - /usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh

How to delete a directory even when it still contains files?

Upvotes: 29

Views: 20027

Answers (3)

Alexander Luna
Alexander Luna

Reputation: 5449

I use bash directly with the system(*args) command like this:

folder = "~/Downloads/remove/this/non/empty/folder"
system("rm -r #{folder}")

It is not really ruby specific but since bash is simpler in this case I use this frequently to cleanup temporary folders and files. The rm command just removes anything you give it and the -r flag tells it to remove files recursively in case the folder is not empty.

Upvotes: 0

Hitesh
Hitesh

Reputation: 825

When you delete a directory with the Dir.delete, it will also search the subdirectories for files.

Dir.delete("/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh")

If the directory was not empty, it will raise Directory not empty error. For that ruby have FiltUtils.rm_r method which will delete the directory no matter what!

require 'fileutils'
FileUtils.rm_r "/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh"

Upvotes: 9

J-_-L
J-_-L

Reputation: 9177

Is not possible with Dir (except iterating through the directories yourself or using Dir.glob and deleting everything).

You should use

require 'fileutils'
FileUtils.rm_r "/usr/local/var/lib/trisul/CONTEXT0/meters/oper/SLICE.9stMxh"

Upvotes: 58

Related Questions