Command Line Arguments in Elixir

Command-line arguments are a common way to parameterize execution of programs. For example, elixir hello.exs uses hello.exs as an argument to the elixir program.

defmodule CommandLineArguments do
  def main do
    # System.argv() provides access to raw command-line
    # arguments. Note that unlike some languages, this does not
    # include the program name as the first argument.
    args_with_prog = [System.get_env("_") | System.argv()]
    args_without_prog = System.argv()

    # You can get individual args with normal list indexing.
    arg = Enum.at(System.argv(), 2)

    IO.inspect(args_with_prog)
    IO.inspect(args_without_prog)
    IO.inspect(arg)
  end
end

CommandLineArguments.main()

To experiment with command-line arguments it’s best to save this code in a file (e.g., command_line_arguments.exs) and run it with elixir.

$ elixir command_line_arguments.exs a b c d
["/usr/local/bin/elixir", "a", "b", "c", "d"]
["a", "b", "c", "d"]
"c"

In Elixir, System.argv() returns a list of command-line arguments, excluding the program name. To include the program name, we’ve used System.get_env("_"), which typically contains the path to the Elixir interpreter.

Next, we’ll look at more advanced command-line processing with option parsing libraries in Elixir.