Environment Variables in Lisp
Our program demonstrates how to work with environment variables in Lisp. 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.
(defun main ()
;; To set a key/value pair, use sb-posix:setenv
;; To get a value for a key, use sb-posix:getenv
;; This will return NIL if the key isn't present in the environment
(sb-posix:setenv "FOO" "1" 1)
(format t "FOO: ~A~%" (sb-posix:getenv "FOO"))
(format t "BAR: ~A~%" (sb-posix:getenv "BAR"))
;; Use sb-ext:posix-environ to list all key/value pairs in the environment
;; This returns a list of strings in the form "KEY=value"
;; You can split them to get the key and value
;; Here we print all the keys
(format t "~%")
(loop for e in (sb-ext:posix-environ)
for pair = (cl-ppcre:split "=" e :limit 2)
do (format t "~A~%" (first pair))))
(main)
To run the program, save it as environment-variables.lisp
and use your Lisp interpreter. For example, if you’re using SBCL:
$ sbcl --script environment-variables.lisp
FOO: 1
BAR: NIL
TERM_PROGRAM
PATH
SHELL
...
FOO
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is NIL (equivalent to empty string in this context).
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 sbcl --script environment-variables.lisp
FOO: 1
BAR: 2
...
Note: This example uses SBCL-specific functions (sb-posix:setenv
, sb-posix:getenv
, sb-ext:posix-environ
). If you’re using a different Lisp implementation, you might need to use different functions or load additional libraries to work with environment variables.