4

I would like to delete a directory using sftp with ruby. Currently I am trying this method (rmdir) from the Net-sftp library of ruby.

Here is my code:

uri = URI(url)
Net::SFTP.start(uri.host, uri.user, :password => uri.password) do |sftp| 
    handle = sftp.opendir!(uri.path)
    sftp.readdir!(handle).each do |item| 
        unless item.name =~ /\.|\.\./
            sftp.rmdir!(uri.path + "/" + item.name)
        end
    end
end

But the only think I could reach is this error:

Net::SFTP::StatusException : Net::SFTP::StatusException (4, "failure")

The directories are not empty, so do I have to recursively delete them one by one, or is there a way to achieve that in a single command?

EDIT

I could manage to delete directories. Two findings needed to be done by me:

  1. directories need to be empty
  2. /\.|\.\./ needs to be /^(\.|\.\.)$/, otherwise files are excluded too, so directories wont ever be empty.

But it is slow to traverse all the directories before deleting them, so, is there a faster way?

philipp
  • 15,947
  • 15
  • 61
  • 106

1 Answers1

4

You could delegate the rmdir to the underlying ssh session instead

sftp.session.exec!("rm -rf #{uri.path}")
jessebs
  • 517
  • 3
  • 14