Command Line Arguments in Crystal

Command-line arguments are a common way to parameterize execution of programs. For example, crystal run hello.cr uses run and hello.cr arguments to the crystal program.

require "option_parser"

# ARGV provides access to raw command-line arguments.
# Note that ARGV[0] is the first argument to the program,
# not the program name as in some other languages.
args_with_prog = ARGV
args_without_prog = ARGV[1..]

# You can get individual args with normal indexing.
arg = ARGV[3]? || ""

puts args_with_prog
puts args_without_prog
puts arg

To experiment with command-line arguments it’s best to save the code in a file and run it with the crystal command.

$ crystal command_line_arguments.cr a b c d
["a", "b", "c", "d"]
["b", "c", "d"]
d

In Crystal, ARGV is an array that contains the command-line arguments passed to the program. Unlike some other languages, ARGV[0] in Crystal is the first argument to the program, not the program name.

The ARGV[1..] syntax creates a new array containing all elements of ARGV from index 1 onwards, effectively removing the first argument.

We use ARGV[3]? with the safe navigation operator ? to avoid an error if there aren’t enough arguments. If the fourth argument doesn’t exist, it will return nil, which we then replace with an empty string using the || operator.

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