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.
open Unix
let () =
(* To set a key/value pair, use Unix.putenv. To get a
value for a key, use Unix.getenv. This will raise
Not_found if the key isn't present in the environment. *)
Unix.putenv "FOO" "1";
Printf.printf "FOO: %s\n" (Unix.getenv "FOO");
Printf.printf "BAR: %s\n" (try Unix.getenv "BAR" with Not_found -> "");
(* Use Unix.environment to list all key/value pairs in the
environment. This returns an array of strings in the
form KEY=value. You can String.split_on_char them to
get the key and value. Here we print all the keys. *)
Printf.printf "\n";
Array.iter (fun e ->
match String.split_on_char '=' e with
| key :: _ -> Printf.printf "%s\n" key
| [] -> ()
) (Unix.environment ())
Running the program shows that we pick up the value for FOO
that we set in the program, but that BAR
is empty.
$ ocaml environment_variables.ml
FOO: 1
BAR:
The list of keys in the environment will depend on your particular machine.
TERM_PROGRAM
PATH
SHELL
...
FOO
If we set BAR
in the environment first, the running program picks that value up.
$ BAR=2 ocaml environment_variables.ml
FOO: 1
BAR: 2
...
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.