Command Line Arguments in Julia

Command-line arguments are a common way to parameterize execution of programs. For example, julia script.jl uses script.jl as an argument to the julia program.

# The PROGRAM_FILE constant provides the name of the script being run
# ARGS is an array of command-line arguments
function main()
    args_with_prog = vcat(PROGRAM_FILE, ARGS)
    args_without_prog = ARGS

    # You can get individual args with normal indexing
    arg = ARGS[3]

    println(args_with_prog)
    println(args_without_prog)
    println(arg)
end

main()

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

$ julia command_line_arguments.jl a b c d
["command_line_arguments.jl", "a", "b", "c", "d"]
["a", "b", "c", "d"]
c

In Julia, command-line arguments are accessed through the global constant ARGS. The PROGRAM_FILE constant gives the name of the script being run, which is equivalent to the first element of os.Args in the original example.

Note that unlike in some other languages, Julia doesn’t require you to declare a main() function or use a special syntax to denote the entry point of the program. The code is executed from top to bottom when you run the script.

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