Command Line Flags in Elixir

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.

Elixir provides the OptionParser module for parsing command-line options. We’ll use this module to implement our example command-line program.

defmodule CommandLineFlags do
  def main(args) do
    # Define the supported options
    options = [
      word: :string,
      numb: :integer,
      fork: :boolean,
      svar: :string
    ]

    # Set default values
    defaults = [
      word: "foo",
      numb: 42,
      fork: false,
      svar: "bar"
    ]

    # Parse the command-line arguments
    {parsed, remaining_args, _} = OptionParser.parse(args, strict: options)

    # Merge parsed options with defaults
    opts = Keyword.merge(defaults, parsed)

    # Print the parsed options and remaining arguments
    IO.puts "word: #{opts[:word]}"
    IO.puts "numb: #{opts[:numb]}"
    IO.puts "fork: #{opts[:fork]}"
    IO.puts "svar: #{opts[:svar]}"
    IO.puts "tail: #{inspect remaining_args}"
  end
end

To experiment with the command-line flags program, you’ll need to compile it and run it as an escript. First, add the following line at the top of your file:

#!/usr/bin/env elixir

Then, make the file executable and run it:

$ chmod +x command_line_flags.exs
$ ./command_line_flags.exs --word=opt --numb=7 --fork --svar=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.exs --word=opt
word: opt
numb: 42
fork: false
svar: bar
tail: []

Trailing positional arguments can be provided after any flags:

$ ./command_line_flags.exs --word=opt a1 a2 a3
word: opt
numb: 42
fork: false
svar: bar
tail: ["a1", "a2", "a3"]

Elixir’s OptionParser doesn’t require flags to appear before positional arguments, which is different from the behavior in some other languages.

To get help text for the command-line program, you would need to implement it yourself, as Elixir doesn’t automatically generate help text like some other languages do.

If you provide a flag that wasn’t specified in the options list, Elixir’s OptionParser will ignore it by default. If you want to raise an error for unknown options, you can pass the strict: true option to OptionParser.parse/2.

This Elixir implementation provides similar functionality to the original example, with some adjustments to fit Elixir’s idioms and the OptionParser module’s capabilities.