Environment Variables in Clojure

Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables in Clojure.

(ns environment-variables
  (:require [clojure.string :as str]))

(defn main []
  ;; To set a key/value pair, use System/setProperty. To get a
  ;; value for a key, use System/getenv. This will return
  ;; nil if the key isn't present in the environment.
  (System/setProperty "FOO" "1")
  (println "FOO:" (System/getenv "FOO"))
  (println "BAR:" (System/getenv "BAR"))

  ;; Use System/getenv to get all key/value pairs in the
  ;; environment. This returns a map of strings.
  ;; Here we print all the keys.
  (println)
  (doseq [k (keys (System/getenv))]
    (println k)))

(main)

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

$ clj environment-variables.clj
FOO: 1
BAR: nil

TERM_PROGRAM
PATH
SHELL
...
FOO

The list of keys in the environment will depend on your particular machine.

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 clj environment-variables.clj
FOO: 1
BAR: 2
...

In Clojure, we use System/setProperty to set environment variables within the program, and System/getenv to retrieve them. The System/getenv function returns a map of all environment variables when called without arguments, which we can use to list all variables.

Note that setting environment variables within a Clojure program using System/setProperty only affects the current JVM instance and doesn’t modify the system-wide environment variables. For persistent changes, you would need to set the variables at the system or shell level before running the Clojure program.