Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating directory over SFTP on Ruby fails if directory exists already

How can I create a directory on Ruby via SFTP only when the directory doesn't exist?

I have the following code right now:

Net::SFTP.start( ip, id, :password => pass, :port=> port ) do |sftp|
    sftp.mkdir! remotePath
    sftp.upload!(localPath + localfile, remotePath + remotefile)
end

I have no problem creating the directory the first time but it tries to recreate the same directory even if it already exists and it throws me an error.

Anyone who knows how to do this?

In using fileutils, there is this code like:

 FileUtils.mkdir_p(remotePath) unless File.exists?(remotePath)

Is there any way I could do the same over SFTP?

like image 624
Laurice Llona Avatar asked May 22 '15 05:05

Laurice Llona


Video Answer


1 Answers

In this case, it may be better to simply "ask for forgiveness", then to "ask for permission". It also eliminates a race condition, where you check if the directory exists, discover it doesn't, and then while creating it you error out because it was created by someone else in the meantime.

The following code will work better:

Net::SFTP.start( ip, id, :password => pass, :port=> port ) do |sftp|
    begin
        sftp.mkdir! remotePath
    rescue Net::SFTP::StatusException => e
        # verify if this returns 11. Your server may return
        # something different like 4.
        if e.code == 11
            # directory already exists. Carry on..
        else 
            raise
        end 
    end
    sftp.upload!(localPath + localfile, remotePath + remotefile)
end
like image 95
14 revs, 12 users 16% Avatar answered Sep 30 '22 11:09

14 revs, 12 users 16%