Environment variables
Every process has a set of named text values, its environment, copied from the process that started it. Settings such as a search path, a language or a log level often travel this way.
'' environ( name ) reads a variable; an unset one reads as "".
print "unset: ["; environ( "BYEXAMPLE_NOT_SET" ); "]"
'' setenviron sets one for this process and the programs it starts.
setenviron "BYEXAMPLE_MODE=draft"
print "BYEXAMPLE_MODE = "; environ( "BYEXAMPLE_MODE" )
'' Setting it again replaces the value.
setenviron "BYEXAMPLE_MODE=final"
print "BYEXAMPLE_MODE = "; environ( "BYEXAMPLE_MODE" )
'' A default for a variable that may be missing.
function EnvOr( byref name_ as ustring, byref fallback as ustring ) _
as ustring
dim as ustring value = environ( name_ )
return iif( len( value ) > 0, value, fallback )
end function
print "BYEXAMPLE_LEVEL = "; EnvOr( "BYEXAMPLE_LEVEL", "3" )
Output
unset: []
BYEXAMPLE_MODE = draft
BYEXAMPLE_MODE = final
BYEXAMPLE_LEVEL = 3
environ( name ) reads a variable. A variable that is not set reads as an
empty string, the same as one set to nothing, so a program that needs a
default writes a helper like EnvOr.
setenviron "NAME=value" sets a variable for this process and for the programs
it starts afterwards, which inherit a copy (see
Running other programs). It never changes the environment of the
shell or program that started yours.
environ returns a string. EnvOr stores it in a ustring before the
iif, because iif needs both of its results to be the same kind of string:
mixing them is TKO0946: iif cannot choose between a narrow string and a ustring.
The example sets its own variables rather than reading PATH or HOME,
because those differ from machine to machine.
Activities
- Set
BYEXAMPLE_LEVELin your shell before running the program, and watchEnvOrreturn it. - Print
environ( "PATH" )and count its entries.