2014-02-14 20 views
0

如何在腳本中使用命令選項?如何在Ruby中使用命令行選項?

我有一個腳本連接到設備,運行命令並打印輸出。我想爲主機使用一個文件,併爲用戶和密碼信息使用一個文件。當我嘗試運行該腳本,我得到這些錯誤:

  1. ruby threat_detection.rb --host_file=hosts --config_file=config

    threat_detection.rb:61:in '<main>': needless argument: --host_file=hosts (OptionParser::NeedlessArgument) 
    
  2. ruby threat_detection.rb '--host_file=hosts' '--config_file=config'

    threat_detection.rb:61:in '<main>': needless argument: --host_file=hosts (OptionParser::NeedlessArgument) 
    
  3. ruby threat_detection.rb --host_file-hosts --config_file-config

    threat_detection.rb:61:in '<main>': invalid option: --host_file-hosts (OptionParser::InvalidOption) 
    

這是代碼:

options ={} 

opt_parser = OptionParser.new do |opt| 
    opt.banner = 'Usage: opt_parser COMMAND [OPTIONS]' 
    opt.on('--host_file', 'I need hosts, put them here') do |host_file| 
    options[:host_file] == host_file 
    end 
    opt.on('--config_file', 'I need config info, put it here') do |config_file| 
    options[:config_file] == config_file 
    end 
    opt.on('-h', '--help', 'What your looking at') do |help| 
    options[:help] == help 
    puts opt 
    end 
end 

opt_parser.parse! 

如何使這些選項得到讀?這是我的猜測(基於python體驗)。我只是在尋找它打印的行現在:

if :config_file == true 
    File.open(:config_file, r) do |params| 
    puts params 
    end 
end 

if :host_file == true 
    File.open(:host_file, r) do |host| 
    put host 
    end 
end 

回答

3

連續服用參數,你需要使用以下格式

"--switch=MANDATORY" or "--switch MANDATORY" # mandatory argument 
"--switch[=OPTIONAL]"      # optional argument 
"--switch"         # no argument 

您目前正在使用的第三格式,它被解釋因爲沒有爭論。你應該使用第一或第二。

另外值得注意的你可能想要做的,而不是分配的比較,當標記是

你要這個

options[:host_file] = host_file 

不是這個

options[:host_file] == host_file