Environment Variables in Co-array Fortran

Our program demonstrates how to work with environment variables in Co-array 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 iso_fortran_env
    implicit none

    character(len=:), allocatable :: foo, bar
    character(len=:), allocatable :: env_var
    integer :: i, status
    character(len=1024) :: buffer
    integer :: count

    ! To set a key/value pair, use the setenv subroutine
    ! To get a value for a key, use the get_environment_variable subroutine
    call setenv("FOO", "1", status)
    call get_environment_variable("FOO", length=count, status=status)
    allocate(character(len=count) :: foo)
    call get_environment_variable("FOO", value=foo, status=status)
    print *, "FOO:", foo

    call get_environment_variable("BAR", length=count, status=status)
    if (status == 0) then
        allocate(character(len=count) :: bar)
        call get_environment_variable("BAR", value=bar, status=status)
        print *, "BAR:", bar
    else
        print *, "BAR: "
    end if

    ! Use get_environment_variable to list all key/value pairs in the environment
    print *
    i = 1
    do
        call get_environment_variable(name=null(), value=buffer, length=count, status=status, trim_name=.true.)
        if (status /= 0) exit
        print *, buffer(1:count)
        i = i + 1
    end do

end program environment_variables

To compile and run the program:

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

TERM_PROGRAM=...
PATH=...
SHELL=...
...
FOO=1

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 Co-array Fortran doesn’t have a direct equivalent to Go’s os.Environ() function. Instead, we’ve used a loop with get_environment_variable to retrieve all environment variables. Also, string handling in Fortran is different from Go, so we’ve had to use allocatable character variables and handle string lengths explicitly.