How to run .clj file as a script using leningen?

17,039

Solution 1

use lein-exec plugin, example from readme.md (updated with "lein" instead of "lein2")

cat foo.clj | lein exec
lein exec -e '(println "foo" (+ 20 30))'
lein exec -ep "(use 'foo.bar) (pprint (map baz (range 200)))"
lein exec -p script/run-server.clj -p 8088
lein exec ~/common/delete-logs.clj

Solution 2

There are several ways with lein repl:

  • Very slow: cat your_file.clj | lein repl
  • Slow: echo '(load-file "your_file.clj")' | lein repl
  • Fast:
    1. lein repl
    2. (load-file "your_file.clj")
    3. repeat 2

Solution 3

leiningen can create an 'uberjar' for you with all your dependencies....

lein uberjar

will create a jar for you in the target subdirectory. The jar will contain all the dependencies listed in your project.clj, so you don't need to worry about constructing a complex classpath to invoke your code.

You can reference this uberjar as a single entry in your java classpath in the normal way or, specify a main-class in the project.clj invoke it as an executable jar.

e.g. a project.clj like this:

(defproject clj-scratch "1.0.0-SNAPSHOT"
 :description "FIXME: write description"
 :dependencies [[org.clojure/clojure "1.4.0"]                     
 :main clj-scratch.core)

will invoke the -main function in clj-scratch.core namespace

if you run:

java -jar target/clj-scratch-1.0.0-SNAPSHOT-standalone.jar
Share:
17,039
Hanfei Sun
Author by

Hanfei Sun

Just another stackoverflow user cs.cmu.edu/~hanfeis

Updated on June 25, 2022

Comments

  • Hanfei Sun
    Hanfei Sun almost 2 years

    This is the second question after Is there a standalone Clojure package within Leiningen?

    For example, I have a file hello_world.clj, and I can run it using

    java -cp clojure.jar clojure.main hello_world.clj.

    Since lein already contains Clojure (because I can run lein repl directly), is there a way to do the same thing like

    lein script hello_world.clj by lein?

  • patentfox
    patentfox over 5 years
    The "fast" one didn't work for me. Had to instead use '(clojure.main/load-script "test.clj")'