2013-04-10 28 views
3

我寫了一個簡單的腳本來檢查Dropbox文件的狀態並將它移動到另一個文件夾,如果文件已被同步並完全下載(狀態=='最新' )。在Ruby中執行一個腳本文件名爲

我現在唯一的問題是,如果文件或目錄中有空格,那麼我的腳本將無法正常運行。

我使用#{...}來傳遞文件名,但似乎它將任何給予它的東西分割成空格。

這裏是我的腳本:

# runs in Ruby 1.8.x (ftools)                      

class DropboxHelper                 

    require 'ftools'                 

    def self.move                  
     directory = "Foo"              
     destination = "Bar"             

     while true                 
      Dir.glob(directory+"/**/*") do |item|          
       next if item == '.' or item == '..'         
       fileStatus = `~/bin/dropbox.py filestatus #{item}`     
       puts "processing " + item            
       puts "filestatus: " + fileStatus          
       if (fileStatus.include? "up to date")         
        puts item.split('/',2)[1] + " is up to date, starting to move file now." 
        `cp -r #{item + " " + destination + "/" + item.split('/',2)[1]} >> copiedFile.out` 

        # remove file in Dropbox folder, if current item is not a directory and 
        # copied file is the identical.         
        if (!File.directory?(item) && File.cmp(item, destination + "/" + item.split('/',2)[1]).to_s) 
         puts "remove " + item           
         `rm -rf #{item} >> removedFile.out`       
        end                
       else                 
        puts item + " is not up to date, moving to next file."   
       end                 
      end                  

      # execute every hour              
      puts "sleeping now"              
      sleep(3600)                
     end                   
    end                    
end                     

DropboxHelper.move 

運行時我得到以下輸出的腳本,如果文件或目錄在他們的空間。它甚至說,文件是不是最新的,但它是:

Foo/Name with spaces is not up to date, moving to next file. 
processing Foo/Name with spaces/file #1.txt 
filestatus: Foo/Name: File doesn't exist 
with:     File doesn't exist 
spaces/file:   File doesn't exist 
Foo/Name with spaces/file #1.txt is not up to date, moving to next file. 

任何建議如何改善和修復代碼?

回答

5

將所有出現的#{item}都用單引號括起來,如'#{item}'。例如:

fileStatus = `~/bin/dropbox.py filestatus '#{item}'` 

您需要這樣做,因爲bash(或您使用的任何shell)以特殊方式解釋空格。由於您的文件名本身包含空格,因此您需要將其轉義。有關更多信息,另請參閱Bash Guide for Beginners中的3.3. Quoting characters