KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Read Environment Variable Using 4D.SystemWorker
PRODUCT: 4D | VERSION: 21 | PLATFORM: Mac & Win
Published On: February 2, 2026
This utility method Reads the value of an OS-level environment variable using 4D.SystemWorker. It handles Windows's echo %VAR% and Unix-like terminal command printenv .

ENV_GetVariable

#DECLARE($varName : Text) : Text

var $value : Text
$value:=""
If($varName="")
   return $value
End if

var $cmd : Text
var $worker : 4D.SystemWorker

If (Is Windows)
   $cmd:="cmd /c echo %"+$varName+"%"
Else
   $cmd:="/bin/sh -c 'printenv "+$varName+"'"
End if

$worker:=4D.SystemWorker.new($cmd)

var $resultObj : Object
$resultObj:=$worker.wait(2)
If ($worker.terminated) && ($worker.exitCode=0)
  
   $value:=$worker.response
   $value:=Trim($value)
  
Else
  
   var $errMsg : Text
   $errMsg:="Failed to read environment variable "+$varName
  
   If ($worker.responseError#"")
      $errMsg:=$errMsg+" - stderr: "+$worker.responseError
   End if
  
   If ($worker.errors#Null) && ($worker.errors.length>0)
      $errMsg:=$errMsg+" - "+JSON Stringify($worker.errors)
   End if
  
   LOG EVENT(Into 4D debug message; $errMsg; Warning message)
  
End if

return $value


Export a variable in your macos or windows Terminal, then run the test.

Windows: set MY_TEST_VAR=This came from Windows Command Prompt
verify with echo %MY_TEST_VAR%

macOS: export MY_TEST_VAR= "This came from macOS terminal"

verify with echo $MY_TEST_VAR
Test Exemple:

var $varName; $value : Text

$varName:="MY_TEST_VAR"

$value:=ENV_GetVariable($varName)