Environment variables
| Get with status | |
| Defaults | |
| Query length first | |
| Env-driven config |
Get with status
Get_environment_variable copies a variable such as APP_MODE into a string. Length reports the true size and status reports problems such as a missing name. Test status before trusting the value.
program env_get
implicit none
character(len=256) :: val
integer :: L, stat
call get_environment_variable("APP_MODE", val, length=L, status=stat)
if (stat == 0) write(*, "(a)") val(1:L)
end program env_get
Defaults
Most settings need a fallback when the variable is absent. Assign the default whenever status is nonzero, then continue as normal. The program then runs both on servers with full config and on plain laptops.
program env_default
implicit none
character(len=256) :: val
integer :: L, stat
call get_environment_variable("APP_MODE", val, length=L, status=stat)
if (stat /= 0) val = "standard"
write(*, "(a)") trim(val)
end program env_default
Query length first
Fixed buffers can truncate long values, so query the length first. Call once with only length and status, allocate exactly that size, then call again to fetch the text. Deferred length strings fit any value with no waste.
program env_len
implicit none
character(len=:), allocatable :: val
integer :: L, stat
call get_environment_variable("APP_MODE", length=L, status=stat)
if (stat == 0) then
allocate(character(len=L) :: val)
call get_environment_variable("APP_MODE", val)
end if
end program env_len
Env-driven config
Environment driven config reads numbers and flags at startup with zero files to ship. Parse each value with an internal read and keep a default for every failure path. Document each name in the usage text so operators know what to export.
program env_cfg
implicit none
character(len=256) :: buf
integer :: nx = 100
integer :: L, stat, ios
call get_environment_variable("NX", buf, length=L, status=stat)
if (stat == 0) read(buf(1:L), *, iostat=ios) nx
print *, nx
end program env_cfg
Next: error stop
Article author: Arthur Isaev