Reading command line arguments

Reading command line arguments

How to:

In Clojure, you snag command line arguments with *command-line-args*. Here’s a simple example:

;; Assume this code is in a file called `echo.clj`

(defn -main [& args]
  (println "You've entered:" args))

;; To run: `clojure echo.clj arg1 arg2 arg3`

Sample output:

You've entered: (arg1 arg2 arg3)

Need to process them? Use Clojure’s collection functions.

(defn -main [& args]
  (let [processed-args (mapv str/upper-case args)]
    (println "Upper-cased:" processed-args)))

;; Now, running `clojure echo.clj hello world` will output:

Sample output:

Upper-cased: ["HELLO" "WORLD"]

Deep Dive

The *command-line-args* is a var in Clojure, set to a sequence of arguments passed to the script. It’s been around since Clojure’s early days, showing Clojure treats command line args as first-class citizens.

Alternatives? Java’s mechanisms for grabbing command line args work in Clojure, too, thanks to interoperability. But that’s more verbose.

As for implementation details, when Clojure starts, it parses the args and stores them in *command-line-args*. Your script can then do whatever with them—parse, ignore, transform, you name it.

See Also