Environment Variables in Ada

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.

with Ada.Text_IO;
with Ada.Environment_Variables;
with Ada.Strings.Unbounded;

procedure Environment_Variables is
   use Ada.Text_IO;
   use Ada.Environment_Variables;
   use Ada.Strings.Unbounded;

begin
   -- To set a key/value pair, use Set. To get a
   -- value for a key, use Value. This will raise
   -- an exception if the key isn't present in the
   -- environment.

   Set ("FOO", "1");
   Put_Line ("FOO: " & Value ("FOO"));
   
   begin
      Put_Line ("BAR: " & Value ("BAR"));
   exception
      when Constraint_Error =>
         Put_Line ("BAR: ");
   end;

   New_Line;

   -- Use Iterate to list all key/value pairs in the
   -- environment. This calls a procedure for each
   -- key/value pair. Here we print all the keys.

   declare
      procedure Print_Key (Name, Value : String) is
      begin
         Put_Line (Name);
      end Print_Key;
   begin
      Iterate (Print_Key'Access);
   end;
end 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.

$ ./environment_variables
FOO: 1
BAR: 

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.

$ export BAR=2
$ ./environment_variables
FOO: 1
BAR: 2
...

In Ada, we use the Ada.Environment_Variables package to work with environment variables. The Set procedure is used to set a variable, and the Value function is used to retrieve a variable’s value. If a variable doesn’t exist, Value will raise a Constraint_Error exception, which we catch to print an empty string for non-existent variables.

To list all environment variables, we use the Iterate procedure, which calls a specified procedure for each environment variable. In this example, we define a local procedure Print_Key that prints only the name of each variable.

Note that Ada’s approach to environment variables is more type-safe than some other languages, as it uses exceptions to handle missing variables rather than returning a special value.