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.
To experiment with command-line arguments it’s best to save the code in a file and run it with the crystal
command.
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.