Jack Gee
Jack Gee

Reputation: 146

Exporting environmental variables in Clojure / Babashka

I am trying to write an install script in babaska for my other babaska script (for some fun homogeneity).

Export doesn't seem to work using:

(shell "export NAME=" value)

Is there a canonical way to set environmental variables in Clojure / Babashka?

Upvotes: 1

Views: 1005

Answers (2)

Michiel Borkent
Michiel Borkent

Reputation: 34820

They way to set environment variables with shell is like this:

(shell {:extra-env {"NAME" "FOOBAR"}} command)

See docs here.

Upvotes: 3

cfrick
cfrick

Reputation: 37033

export is shell built-in; you can not call it outside a shell. So what you want to do instead is run your command with another environment. This can be done in sh with the :env option. E.g.

(-> (shell/sh "sh" "-c" "echo $X" :env {"X" "Hello"}) :out)

edit: global state for environment

At least on the JVM, there is no easy way to change the environment. So you are better off, writing your own function to do the calls and merge with your own global environment.

This example uses an atom to keep the environment around:

(def sh-env (atom {}))

(defn export!
  [m]
  (swap! sh-env merge m))

(defn sh
  ([cmd]
   (sh cmd {}))
  ([cmd env]
   (apply shell/sh (concat cmd [:env (merge @sh-env env)]))))

;;;

(def echo ["sh" "-c" "echo $X"])

(prn (sh echo))

(export! {"X" "Hello"})

(prn (sh echo))

(prn (sh echo {"X" "Goodbye"}))

(export! {"X" "Goodbye"})

(prn (sh echo))

; {:exit 0, :out "\n", :err ""}
; {:exit 0, :out "Hello\n", :err ""}
; {:exit 0, :out "Goodbye\n", :err ""}
; {:exit 0, :out "Goodbye\n", :err ""}

Upvotes: 2

Related Questions