Command Line Flags in Crystal

Our first program demonstrates how to use command-line flags in Crystal. Command-line flags are a common way to specify options for command-line programs. For example, in wc -l the -l is a command-line flag.

require "option_parser"

# Define variables to store the flag values
word = "foo"
numb = 42
fork = false
svar = "bar"

# Set up the OptionParser
OptionParser.parse do |parser|
  parser.banner = "Usage: command-line-flags [arguments]"

  # Define the flags
  parser.on("-w WORD", "--word=WORD", "a string") { |w| word = w }
  parser.on("-n NUMBER", "--numb=NUMBER", "an int") { |n| numb = n.to_i }
  parser.on("-f", "--fork", "a bool") { fork = true }
  parser.on("-s SVAR", "--svar=SVAR", "a string var") { |s| svar = s }
  parser.on("-h", "--help", "Show this help") do
    puts parser
    exit
  end
end

# Print out the parsed options
puts "word: #{word}"
puts "numb: #{numb}"
puts "fork: #{fork}"
puts "svar: #{svar}"
puts "tail: #{ARGV}"

To experiment with the command-line flags program, first compile it and then run the resulting binary directly.

$ crystal build command-line-flags.cr

Try out the built program by first giving it values for all flags.

$ ./command-line-flags -w opt -n 7 -f -s flag
word: opt
numb: 7
fork: true
svar: flag
tail: []

Note that if you omit flags, they automatically take their default values.

$ ./command-line-flags -w opt
word: opt
numb: 42
fork: false
svar: bar
tail: []

Trailing positional arguments can be provided after any flags.

$ ./command-line-flags -w opt a1 a2 a3
word: opt
...
tail: ["a1", "a2", "a3"]

Use -h or --help flags to get automatically generated help text for the command-line program.

$ ./command-line-flags -h
Usage: command-line-flags [arguments]
    -w WORD, --word=WORD             a string
    -n NUMBER, --numb=NUMBER         an int
    -f, --fork                       a bool
    -s SVAR, --svar=SVAR             a string var
    -h, --help                       Show this help

If you provide a flag that wasn’t specified to the OptionParser, the program will print an error message and show the help text again.

$ ./command-line-flags -x
Invalid option: -x
Usage: command-line-flags [arguments]
...

In Crystal, we use the OptionParser class to handle command-line flags. It provides a flexible way to define and parse command-line options. The syntax is different from Go’s flag package, but the concept is similar. We define the flags using the on method of the OptionParser, and then parse the command-line arguments. The parsed values are stored in variables that we can use in our program.