Environment Variables in OCaml
Our program demonstrates how to work with environment variables in OCaml. 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.
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is empty.
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.
In OCaml, we use the Unix
module to interact with environment variables. The Unix.putenv
function is used to set environment variables, while Unix.getenv
is used to retrieve them. The Unix.environment
function returns an array of all environment variables.
Note that unlike in some other languages, retrieving a non-existent environment variable in OCaml raises a Not_found
exception, which we handle in our example to provide an empty string as a default value.