system_getenv Function

public function system_getenv(name, default) result(value)

NAME

system_getenv(3f) - [M_system:ENVIRONMENT] get environment variable
from Fortran by calling get_environment_variable(3f)
(LICENSE:PD)

SYNOPSIS

function system_getenv(name,default)

 character(len=:),allocatable         :: system_getenv
 character(len=*),intent(in)          :: name
 character(len=*),intent(in),optional :: default

DESCRIPTION

The system_getenv() function gets the value of an environment variable.

OPTIONS

name     Return the value of the specified environment variable or
         blank if the variable is not defined.
default  If the value returned would be blank this value will be used
         instead.

EXAMPLE

Sample setting an environment variable from Fortran:

program demo_system_getenv
use M_system, only : system_getenv
use M_system, only : ge=>system_getenv
implicit none
character(len=:),allocatable :: TMPDIR

   write(*,'("USER     : ",a)')system_getenv('USER')
   write(*,'("LOGNAME  : ",a)')system_getenv('LOGNAME')
   write(*,'("USERNAME : ",a)')system_getenv('USERNAME')

   ! look first for USER then LOGNAME then USERNAME
   write(*, *)ge('USER', ge('LOGNAME', ge('USERNAME', 'UNKNOWN')))

   TMPDIR= ge('TMPDIR', ge('TMP', ge('TEMPDIR', ge('TEMP', '/tmp'))))
   write(*,*)'favorite scratch area is ',TMPDIR

end program demo_system_getenv

AUTHOR

John S. Urban

LICENSE

Public Domain

Arguments

Type IntentOptional Attributes Name
character(len=*), intent(in) :: name
character(len=*), intent(in), optional :: default

Return Value character(len=:), allocatable


Contents

Source Code


Source Code

function system_getenv(name,default) result(value)

! ident_23="@(#) M_system system_getenv(3f) call get_environment_variable as a function with a default value(3f)"

character(len=*),intent(in)          :: name
character(len=*),intent(in),optional :: default
integer                              :: howbig
integer                              :: stat
character(len=:),allocatable         :: value

   if(NAME.ne.'')then
      call get_environment_variable(name, length=howbig, status=stat, trim_name=.true.)  ! get length required to hold value
      if(howbig.ne.0)then
         select case (stat)
         case (1)     ! print *, NAME, " is not defined in the environment. Strange..."
            value=''
         case (2)     ! print *, "This processor doesn't support environment variables. Boooh!"
            value=''
         case default ! make string to hold value of sufficient size and get value
            if(allocated(value))deallocate(value)
            allocate(character(len=max(howbig,1)) :: VALUE)
            call get_environment_variable(name,value,status=stat,trim_name=.true.)
            if(stat.ne.0)VALUE=''
         end select
      else
         value=''
      endif
   else
      value=''
   endif
   if(value.eq.''.and.present(default))value=default

end function system_getenv