Environment Variables in Scheme

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 Scheme.

(use-modules (ice-9 popen)
             (ice-9 rdelim))

;; To set a key/value pair, we can use setenv
;; To get a value for a key, we can use getenv
;; getenv will return #f if the key isn't present in the environment
(setenv "FOO" "1")
(display "FOO: ") (display (getenv "FOO")) (newline)
(display "BAR: ") (display (getenv "BAR")) (newline)

;; To list all key/value pairs in the environment, we can use the environ variable
;; This returns an association list of strings in the form (KEY . value)
;; Here we print all the keys
(newline)
(for-each 
  (lambda (pair)
    (display (car pair))
    (newline))
  (environ))

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty (represented as #f in Scheme).

FOO: 1
BAR: #f

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 guile environment-variables.scm
FOO: 1
BAR: 2
...

In Scheme, we use setenv to set environment variables and getenv to retrieve them. The environ variable gives us access to all environment variables as an association list. We can use Scheme’s list processing functions to work with this data.

Note that the exact behavior might vary slightly depending on the Scheme implementation you’re using. This example uses GNU Guile, which is one of the more popular Scheme implementations.