Environment Variables

Fortran 2003 introduced an intrinsic procedure to easily access global environment variables of the operating system. Arbitrary user-defined and system-wide variables can be accessed in Fortran, for instance, HOME, CHARSET, or LANG.

call get_environment_variable(name[, value][, length][, status][, trim_name])
Argument Type Description
name character Name of the environment variable.
value character Value of the environment variable (optional).
length integer Length of the requested environment variable on return (optional).
status integer Returns 0 on success, -1 if value was too short to contain the actual variable, 1 if environment variable does not exist, and 2 if environment variables are not supported (optional).
trim_name logical If .false., trailing blanks in name are significant (optional).

The following example reads in the user-defined environment variable SECRET_PASSWORD:

! example.f90
program main
    implicit none
    character(len=32) :: password
    integer           :: length
    integer           :: rc

    call get_environment_variable('SECRET_PASSWORD', password, length, rc)

    if (rc == 0) then
        print '(2a)', 'Password: ', trim(password)
    end if
end program main

The variable has to be set in advance. In KornShell, we simply call export:

$ export SECRET_PASSWORD="correct.horse.battery.staple"
$ gfortran10 -o example example.f90
$ ./example
Password: correct.horse.battery.staple

In tcsh, we would have to run setenv instead:

$ setenv SECRET_PASSWORD correct.horse.battery.staple