The Crystal Programming Language Forum

Command Line Arguments

I’m having some trouble finding documentation of implementing command-line arguments. I found something called option_parser, but did not find examples of it taking input from the user. I found other examples of taking user arguments with
ARGV, but they had no parameters. I tried inserting ARGV into an example I had with option_parser, but this and other attempts I made did not work:

 require "option_parser"
  
 string = "echo "
  
 OptionParser.parse do |parser|
    parser.banner = "Genric Banner"
  
    parser.on "-e", "--execute", "Execute commands" do
      ARGV
      exit
    end
    parser.on "-v", "--version", "Show version" do
      puts "version 1.0"
      exit
    end
    parser.on "-h", "--help", "Show help" do
      puts parser
      exit
    end
  end
  
  y = "#{string}#{ARGV}"
  
  Process.run(y, shell: true) do |proc|
    IO.copy(proc.output, STDOUT)
  end

I’m unsure of the best way to do this. If ARGV is needed, I’ll probably need to ask how to do with with multiple arguments. Any feedback appreciated.

Using the example from https://crystal-lang.org/api/master/OptionParser.html.

crystal build app.cr
./app -h
./app --upcase -t Jim
2 Likes

Interesting, I was taken to a part of that same wiki earlier, but not the OptionParser section. I must have been googling something wrong. This I can work with. Thank you.

1 Like

np. I’d also check out https://crystal-lang.org/reference/getting_started/cli.html if you haven’t.

1 Like

Also 2 goods shards for handling CLI:

Support sub-commands and other handy features

1 Like