简体   繁体   中英

How do I use command-line options in Ruby?

How do I use command options in scripts?

I have a script that connects to a device, runs commands and prints the output. I would like to use a file for the hosts, and one for the user and passwd info. When I try to run the script I get these errors:

  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) 

This is the code:

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!

How do I make these options get read? This is my guess (based off python experience). I'm just looking for it to print the lines right now:

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

For taking arguments you need to use the following formats

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

You are currently using the third format, which is being interpreted as taking no argument. You should use the first or second.

Also worth noting you probably want to be doing an assignment instead of a comparison when a flag is on

You want this

options[:host_file] = host_file

not this

options[:host_file] == host_file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM