Environment Variables in Racket

Our program demonstrates how to work with environment variables in Racket. Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables.

#lang racket

(require racket/environment)

(define (main)
  ; To set a key/value pair, use `putenv`. To get a
  ; value for a key, use `getenv`. This will return
  ; #f if the key isn't present in the environment.
  (putenv "FOO" "1")
  (printf "FOO: ~a\n" (getenv "FOO"))
  (printf "BAR: ~a\n" (getenv "BAR"))

  ; Use `environment-variables-names` to list all keys in the
  ; environment. This returns a list of strings.
  ; Here we print all the keys.
  (printf "\n")
  (for ([name (environment-variables-names)])
    (printf "~a\n" name)))

(main)

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

$ racket environment-variables.rkt
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.

$ env BAR=2 racket environment-variables.rkt
FOO: 1
BAR: 2
...

In Racket, we use putenv to set environment variables and getenv to retrieve them. The environment-variables-names function gives us a list of all environment variable names. Unlike Go, Racket doesn’t provide a direct equivalent to os.Environ() that returns both keys and values, so we’ve focused on printing just the keys in this example.