functionexpand_vars
character(len=:) function expand_vars(path) result(out)
path with $NAME and ${NAME} replaced by environment variables. Unset variables are left
as written.
Arguments
| Name | Type | Intent | Attributes | Description |
|---|---|---|---|---|
| path | character(len=*) | in | the text |
Result
| Name | Type | Attributes | Description |
|---|---|---|---|
| out | character(len=:) | privateallocatable |
Source
Show the code
function expand_vars(path) result(out)
character(len=*), intent(in) :: path !! the text
character(len=:), allocatable :: out, name, value
character(len=*), parameter :: NAME_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_'
integer :: i, j, n, stat
logical :: braced
out = ''
i = 1
do while (i <= len(path))
if (path(i:i) /= '$') then
out = out//path(i:i)
i = i + 1
cycle
end if
braced = .false.
if (i < len(path)) braced = path(i + 1:i + 1) == '{'
if (braced) then
j = index(path(i + 2:), '}')
if (j > 0) j = i + 1 + j
else
j = verify(path(i + 1:), NAME_CHARS)
j = merge(len(path), i + j - 1, j == 0)
end if
if (j == 0 .or. j == i) then
out = out//'$'
i = i + 1
cycle
end if
if (braced) then
name = path(i + 2:j - 1)
else
name = path(i + 1:j)
end if
call get_environment_variable(name, length=n, status=stat)
if (stat == 0) then
allocate (character(len=n) :: value)
call get_environment_variable(name, value)
out = out//value
deallocate (value)
else
out = out//path(i:j)
end if
i = j + 1
end do
end function expand_vars