Command Line Arguments in Clojure

In Clojure, command-line arguments are accessed through the *command-line-args* special variable. Here’s how we can work with command-line arguments:

(ns command-line-arguments
  (:require [clojure.string :as str]))

(defn -main [& args]
  (let [args-with-prog (cons *file* args)
        args-without-prog args
        arg (nth args 2)]
    (println args-with-prog)
    (println args-without-prog)
    (println arg)))

The *command-line-args* sequence provides access to raw command-line arguments. Note that unlike in some other languages, this sequence does not include the program name as its first element.

In our example, we’re using *file* to get the name of the current file, which is similar to getting the program name. We then use cons to prepend this to the arguments list to create args-with-prog.

You can get individual args with normal indexing using the nth function. Remember that Clojure uses zero-based indexing.

To experiment with command-line arguments, it’s best to create a script or compile to a JAR file first. Here’s how you might run it:

$ clj -m command-line-arguments a b c d
(command_line_arguments.clj a b c d)
(a b c d)
c

In this example, we’re using clj to run our Clojure program directly. The -m flag specifies the namespace to use as the entry point.

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