Environment Variables in Fortran

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

program environment_variables
  use, intrinsic :: iso_fortran_env
  use, intrinsic :: iso_c_binding
  implicit none

  character(len=:), allocatable :: value
  integer :: i, status
  character(len=1024) :: env_var

  ! To set a key/value pair, use setenv from the C library
  call set_environment_variable("FOO", "1", status)
  if (status /= 0) then
    print *, "Error setting environment variable"
    stop
  end if

  ! To get a value for a key, use get_environment_variable
  call get_environment_variable("FOO", value, status=status)
  if (status == 0) then
    print *, "FOO:", value
  else
    print *, "FOO: not set"
  end if

  call get_environment_variable("BAR", value, status=status)
  if (status == 0) then
    print *, "BAR:", value
  else
    print *, "BAR: not set"
  end if

  ! To list all environment variables
  print *
  i = 1
  do
    call get_environment_variable(name=env_var, value=value, status=status, trim_name=.true.)
    if (status /= 0) exit
    print *, trim(env_var)
    i = i + 1
  end do

contains

  subroutine set_environment_variable(name, value, status)
    use, intrinsic :: iso_c_binding
    character(len=*), intent(in) :: name, value
    integer, intent(out) :: status
    interface
      function setenv(name, value, overwrite) bind(c, name="setenv")
        import
        integer(c_int) :: setenv
        character(kind=c_char), intent(in) :: name(*), value(*)
        integer(c_int), value :: overwrite
      end function setenv
    end interface
    status = setenv(trim(name)//c_null_char, trim(value)//c_null_char, 1_c_int)
  end subroutine set_environment_variable

end program 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.

$ gfortran environment_variables.f90 -o environment_variables
$ ./environment_variables
FOO: 1
BAR: not set

PATH
HOME
USER
...
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
...

Note that Fortran doesn’t have built-in functions for setting environment variables, so we use the C library function setenv through an interface. The get_environment_variable intrinsic function is used to retrieve environment variable values and list all environment variables.