2014-02-14 21 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