Environment Variables

Fortran 2003 introduced an intrinsic procedure to easily access global environment variables. Arbitrary user-defined and system-wide variables can be accessed from Fortran, such as HOME, CHARSET, or LANG.

call get_environment_variable(name[, value][, length][, status][, trim_name][, errmsg])
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).
errmsg character Returns error message, since Fortran 2018 (optional).

The following example reads 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) return

    print '("Password: ", a)', trim(password)
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 to set the environment variable:

$ setenv SECRET_PASSWORD "correct.horse.battery.staple"

To prevent any sensitive data to be exposed to the shell history, we can run read to retrieve the passphrase:

$ read SECRET_PASSWORD
correct.horse.battery.staple
$ ./example
Password: correct.horse.battery.staple