Command Line Arguments in Nim

Command-line arguments are a common way to parameterize execution of programs. For example, nim c -r hello.nim uses c, -r, and hello.nim arguments to the nim program.

import os

# The commandLineParams() proc provides access to raw command-line
# arguments. Note that the first value returned by this proc
# is the first argument to the program, not the program name itself.

let argsWithoutProg = commandLineParams()
let argsWithProg = getAppFilename() & argsWithoutProg

# You can get individual args with normal indexing.
let arg = paramStr(3)

echo argsWithProg
echo argsWithoutProg
echo arg

To experiment with command-line arguments it’s best to compile the program first.

$ nim c command_line_arguments.nim
$ ./command_line_arguments a b c d
/path/to/command_line_arguments a b c d
@["a", "b", "c", "d"]
c

In Nim, we use the os module to access command-line arguments. The commandLineParams() proc returns a sequence of strings containing all command-line arguments, excluding the program name. To get the program name, we use getAppFilename().

The paramStr() proc allows us to access individual arguments by index, with paramStr(0) being the program name and paramStr(1) onwards being the actual arguments.

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