UVTC's Blog


To create a script in Clojure (well, a small program that fits into one single file and doesn’t need an actual project within which to live), one good option is to use the lein-exec Leiningen plug-in.

However, if for whatever reason you want to pull in your script’s dependencies yourself (and not use the plug-in), you can. Here’s how.

Create a ~/bin/lein-run file. Into it put:


lein run -m clojure.main/main -i "$@"

Then chmod +x ~/bin/lein-run.

Note: the -m option is to the lein run subcommand/task. The -i option is to clojure.main/main (“‘-i, –init path’ Load a file or resource”).

Then create a template file, copies of which you can modify to suit your needs. Possibly name it ~/tmpl/clj-lein-run.clj:

#!/usr/bin/env lein-run

(require '[cemerick.pomegranate :as pome])

 :coordinates '[[org.clojure/math.combinatorics "0.0.4"]]
 :repositories (merge cemerick.pomegranate.aether/maven-central
                      {"clojars" "http://clojars.org/repo"}))

(require '[clojure.math.combinatorics :as combo])

(println "hi" (combo/combinations [1 2 3] 2))

Then chmod +x it.

You can now run that file like any other executable script. :)

To modify copies for other uses, just change the lines where math.combinatorics appears.

Thanks technomancy and xeqi in #leiningen for the help; and Shantanu for the example code in lein-exec!