Environment variables: Difference between revisions

From Rosetta Code
Content added Content deleted
(→‎{{header|PARI/GP}}: Echoing an environment variable in a child process shell is not environment access (unless you capture the output).)
(Add SmallBASIC)
 
(140 intermediate revisions by 83 users not shown)
Line 1: Line 1:
{{task|Programming environment operations}}
{{task|Programming environment operations}}
[[Category:Environment variables]]
Show how to get one of your process's [[wp:Environment variable|environment variables]]. The available variables vary by system; some of the common ones available on Unix include PATH, HOME, USER.
[[Category:Initialization]]
[[Category:Simple]]
{{omit from|M4}}
{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} <!-- Does not have an environment other than regular global variables. -->
{{omit from|Unlambda|Does not provide access to environment variables.}}

;Task:
Show how to get one of your process's [[wp:Environment variable|environment variables]].

The available variables vary by system; &nbsp; some of the common ones available on Unix include:
:::* &nbsp; PATH
:::* &nbsp; HOME
:::* &nbsp; USER
<br><br>

=={{header|11l}}==
<syntaxhighlight lang="11l">print(os:getenv(‘HOME’))</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==
Print a single environment variable.
Print a single environment variable.
<lang ada>with Ada.Environment_Variables; use Ada.Environment_Variables;
<syntaxhighlight lang="ada">with Ada.Environment_Variables; use Ada.Environment_Variables;
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Text_Io; use Ada.Text_Io;


Line 10: Line 27:
begin
begin
Put_Line("Path : " & Value("PATH"));
Put_Line("Path : " & Value("PATH"));
end Print_Path;</lang>
end Print_Path;</syntaxhighlight>
Print all environment variable names and values.
Print all environment variable names and values.
<lang ada>with Ada.Environment_Variables; use Ada.Environment_Variables;
<syntaxhighlight lang="ada">with Ada.Environment_Variables; use Ada.Environment_Variables;
with Ada.Text_Io; use Ada.Text_Io;
with Ada.Text_Io; use Ada.Text_Io;


Line 22: Line 39:
begin
begin
Iterate(Print_Vars'access);
Iterate(Print_Vars'access);
end Env_Vars;</lang>
end Env_Vars;</syntaxhighlight>


=== Alternative version using Matreshka ===

Uses [http://forge.ada-ru.org/matreshka Matreshka].

<syntaxhighlight lang="ada">with Ada.Wide_Wide_Text_IO;

with League.Application;
with League.Strings;

procedure Main is

function "+"
(Item : Wide_Wide_String) return League.Strings.Universal_String
renames League.Strings.To_Universal_String;

begin
Ada.Wide_Wide_Text_IO.Put_Line
(League.Application.Environment.Value (+"HOME").To_Wide_Wide_String);
end Main;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386 - ''getenv'' is not part of the standard's prelude}}
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386 - ''getenv'' is not part of the standard's prelude}}
<lang algol68>print((getenv("HOME"), new line))</lang>
<syntaxhighlight lang="algol68">print((getenv("HOME"), new line))</syntaxhighlight>

=={{header|APL}}==
<syntaxhighlight lang="apl">
⎕ENV 'HOME'
HOME /home/russtopia
</syntaxhighlight>

=={{header|AppleScript}}==
===Invoking Finder===
<syntaxhighlight lang="applescript">
tell application "Finder" to get name of home
</syntaxhighlight>
===Invoking Terminal===
<syntaxhighlight lang="applescript">
"HOME : " & (do shell script "echo $HOME" & ", PATH : " & (do shell script "echo $PATH" & ", USER : " & (do shell script "echo $USER")))
</syntaxhighlight>

=={{header|Arturo}}==

<syntaxhighlight lang="rebol">print ["path:" env\PATH]
print ["user:" env\USER]
print ["home:" env\HOME]</syntaxhighlight>

{{out}}

<pre>path: /Users/drkameleon/.arturo/bin:/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
user: drkameleon
home: /Users/drkameleon</pre>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang autohotkey>EnvGet, OutputVar, Path
<syntaxhighlight lang="autohotkey">EnvGet, OutputVar, Path
MsgBox, %OutputVar%</lang>
MsgBox, %OutputVar%</syntaxhighlight>

=={{header|AutoIt}}==
<syntaxhighlight lang="autoit">ConsoleWrite("# Environment:" & @CRLF)

Local $sEnvVar = EnvGet("LANG")
ConsoleWrite("LANG : " & $sEnvVar & @CRLF)

ShowEnv("SystemDrive")
ShowEnv("USERNAME")

Func ShowEnv($N)
ConsoleWrite( StringFormat("%-12s : %s\n", $N, EnvGet($N)) )
EndFunc ;==>ShowEnv</syntaxhighlight>

{{Out}}
<pre># Environment:
LANG : DE
SystemDrive : C:
USERNAME : HaJo</pre>


=={{header|AWK}}==
=={{header|AWK}}==
The ENVIRON array contains the values of the current environment:
The ENVIRON array contains the values of the current environment:
<lang awk>$ awk 'BEGIN{print "HOME:"ENVIRON["HOME"],"USER:"ENVIRON["USER"]}'
<syntaxhighlight lang="awk">$ awk 'BEGIN{print "HOME:"ENVIRON["HOME"],"USER:"ENVIRON["USER"]}' </syntaxhighlight>
{{out}}
HOME:/home/suchrich USER:SuchRich</lang>
<pre>
HOME:/home/suchrich USER:SuchRich</pre>

Environment variables can also be assigned to awk variables before execution, with (-v) options:
Environment variables can also be assigned to awk variables before execution, with (-v) options:
<lang awk>$ awk -v h=$HOME -v u=$USER 'BEGIN{print "HOME:"h,"USER:"u}'
<syntaxhighlight lang="awk">$ awk -v h=$HOME -v u=$USER 'BEGIN{print "HOME:"h,"USER:"u}' </syntaxhighlight>
{{out}}
HOME:/home/suchrich USER:SuchRich</lang>
<pre>HOME:/home/suchrich USER:SuchRich</pre>

Listing all the environment variables:
<syntaxhighlight lang="awk"># http://ideone.com/St5SHF
BEGIN { print "# Environment:"
for (e in ENVIRON) { printf( "%10s = %s\n", e, ENVIRON[e] ) }
}
END { print "# Done." } </syntaxhighlight>
{{out}}
<pre>
# Environment:
AWKPATH = .:/usr/share/awk
AWKLIBPATH = /usr/lib/i386-linux-gnu/gawk
LANG = en_US.UTF-8
PATH = /usr/local/bin:/usr/bin:/bin
HOME = /home/guest
PWD = /home/guest
SHLVL = 0
TMPDIR = /home/guest
# Done.

</pre>


=={{header|BASIC}}==
=={{header|BASIC}}==
<lang qbasic>x$ = ENVIRON$("path")
<syntaxhighlight lang="qbasic">x$ = ENVIRON$("path")
PRINT x$
PRINT x$</syntaxhighlight>
</lang>


=== {{header|ZX Spectrum Basic}} ===
==={{header|BaCon}}===
''Case matters and needs to match''
<syntaxhighlight lang="freebasic">PRINT GETENVIRON$("PATH")</syntaxhighlight>


==={{header|IS-BASIC}}===
The ZX Spectrum does not use environmental variables in a traditional sense. However, it does provide a set of system variables held at a fixed memory address:
<syntaxhighlight lang="is-basic">100 ASK BORDER VAR01
110 ASK DEFAULT CHANNEL VAR02
120 ASK EDITOR BUFFER VAR03
130 ASK EDITOR KEY VAR04
140 ASK EDITOR VIDEO VAR05
150 ASK FAST SAVE VAR06
160 ASK INTERRUPT KEY VAR07
170 ASK INTERRUPT NET VAR08
180 ASK INTERRUPT STOP VAR09
190 ASK KEY CLICK VAR10
200 ASK KEY DELAY VAR11
210 ASK KEY RATE VAR12
220 ASK NET CHANNEL VAR13
230 ASK NET MACHINE VAR14
240 ASK REM1 VAR15
250 ASK REM2 VAR16
260 ASK SERIAL BAUD VAR17
270 ASK SERIAL FORMAT VAR18
280 ASK STATUS VAR19
290 ASK SOUND BUFFER VAR20
300 ASK SPEAKER VAR21
310 ASK TAPE LEVEL VAR22
320 ASK TAPE SOUND VAR23
330 ASK TIMER VAR24
340 ASK VIDEO COLOR VAR25
350 ASK VIDEO MODE VAR26
360 ASK VIDEO X VAR27
370 ASK VIDEO Y VAR28</syntaxhighlight>


or
<lang zxbasic>

10 PRINT "The border colour is "; PEEK (23624): REM bordcr
<syntaxhighlight lang="is-basic">ASK machine-option-code var</syntaxhighlight>

==={{header|SmallBASIC}}===
<syntaxhighlight lang="qbasic">
print env("HOME")
print env("PATH")
print env("USER")
</syntaxhighlight>

==={{header|ZX Spectrum Basic}}===
The ZX Spectrum does not use environmental variables in a traditional sense. However, it does provide a set of system variables held at a fixed memory address:
<syntaxhighlight lang="zxbasic">10 PRINT "The border colour is "; PEEK (23624): REM bordcr
20 PRINT "The ramtop address is "; PEEK (23730) + 256 * PEEK (23731): REM ramtop
20 PRINT "The ramtop address is "; PEEK (23730) + 256 * PEEK (23731): REM ramtop
30 POKE 23609,50: REM set keyboard pip to 50
30 POKE 23609,50: REM set keyboard pip to 50</syntaxhighlight>
</lang>


=={{header|Batch File}}==
=={{header|Batch File}}==
Batch files don't have any other kind of variables except environment variables. They can be accessed by enclosing the variable name in percent signs:
Batch files don't have any other kind of variables except environment variables. They can be accessed by enclosing the variable name in percent signs:
<lang dos>echo %Foo%</lang>
<syntaxhighlight lang="dos">echo %Foo%</syntaxhighlight>
For interactive use one can use <code>set</code> to view all environment variables or all variables starting with a certain string:
For interactive use one can use <code>set</code> to view all environment variables or all variables starting with a certain string:
<lang dos>set
<syntaxhighlight lang="dos">set
set Foo</lang>
set Foo</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> PRINT FNenvironment("PATH")
<syntaxhighlight lang="bbcbasic"> PRINT FNenvironment("PATH")
PRINT FNenvironment("USERNAME")
PRINT FNenvironment("USERNAME")
END
END
Line 73: Line 223:
DIM buffer% LOCAL size%
DIM buffer% LOCAL size%
SYS "GetEnvironmentVariable", envar$, buffer%, size%+1
SYS "GetEnvironmentVariable", envar$, buffer%, size%+1
= $$buffer%</lang>
= $$buffer%</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdlib.h>
<syntaxhighlight lang="c">#include <stdlib.h>
#include <stdio.h>
#include <stdio.h>

int main() {
int main() {
puts(getenv("HOME"));
puts(getenv("HOME"));
puts(getenv("PATH"));
puts(getenv("USER"));
return 0;
return 0;
}
}</lang>
</syntaxhighlight>

=={{header|C++}}==
<lang cpp>#include <cstdlib>
#include <cstdio>

int main()
{
puts(getenv("HOME"));
return 0;
}</lang>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System;
<syntaxhighlight lang="csharp">using System;


namespace RosettaCode {
namespace RosettaCode {
Line 104: Line 247:
}
}
}
}
}</lang>
}</syntaxhighlight>

=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <cstdlib>
#include <cstdio>

int main()
{
puts(getenv("HOME"));
return 0;
}</syntaxhighlight>


=={{header|Clojure}}==
=={{header|Clojure}}==
<syntaxhighlight lang="lisp">(System/getenv "HOME")</syntaxhighlight>
<lang lisp>
(System/getenv "HOME")
</lang>


=={{header|D}}==
=={{header|COBOL}}==
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
{{libheader|phobos}}
PROGRAM-ID. Environment-Vars.


DATA DIVISION.
<lang d>import std.stdio, std.process;
WORKING-STORAGE SECTION.
01 home PIC X(75).


PROCEDURE DIVISION.
void main() {
* *> Method 1.
writeln(getenv("HOME"));
ACCEPT home FROM ENVIRONMENT "HOME"
}</lang>
DISPLAY home


* *> Method 2.
{{libheader|tango}}
DISPLAY "HOME" UPON ENVIRONMENT-NAME
<lang d>import tango.sys.Environment;
ACCEPT home FROM ENVIRONMENT-VALUE


GOBACK
void main() {
.</syntaxhighlight>
auto home = Environment("HOME");

}</lang>
=={{header|CoffeeScript}}==
{{works with|node.js}}
<syntaxhighlight lang="coffeescript">for var_name in ['PATH', 'HOME', 'LANG', 'USER']
console.log var_name, process.env[var_name]</syntaxhighlight>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==

Access to environment variables isn't a part of the Common Lisp standard, but most implementations provide some way to do it.
Access to environment variables isn't a part of the Common Lisp standard, but most implementations provide some way to do it.

{{works with|LispWorks}}
{{works with|LispWorks}}
<syntaxhighlight lang="lisp">(lispworks:environment-variable "USER")</syntaxhighlight>

<lang lisp>(lispworks:environment-variable "USER")</lang>

{{works with|SBCL}}
{{works with|SBCL}}
<syntaxhighlight lang="lisp">(sb-ext:posix-getenv "USER")</syntaxhighlight>

<lang lisp>(sb-ext:posix-getenv "USER")</lang>

{{works with|Clozure CL}}
{{works with|Clozure CL}}
<syntaxhighlight lang="lisp">(ccl:getenv "USER")</syntaxhighlight>
{{works with|CLISP}}
<syntaxhighlight lang="lisp">(getenv "HOME")</syntaxhighlight>
Ways to do this in some other implementations are listed in the [http://cl-cookbook.sourceforge.net/os.html#env Common Lisp Cookbook].


=={{header|D}}==
<lang lisp>(ccl:getenv "USER")</lang>
{{libheader|phobos}}
<syntaxhighlight lang="d">import std.stdio, std.process;


void main() {
Ways to do this in some other implementations are listed in the [http://cl-cookbook.sourceforge.net/os.html#env Common Lisp Cookbook].
auto home = getenv("HOME");
}</syntaxhighlight>
{{libheader|tango}}
<syntaxhighlight lang="d">import tango.sys.Environment;

void main() {
auto home = Environment("HOME");
}</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}/{{header|Pascal}}==
<lang Delphi>program EnvironmentVariable;
<syntaxhighlight lang="delphi">program EnvironmentVariable;


{$APPTYPE CONSOLE}
{$APPTYPE CONSOLE}
Line 154: Line 322:
begin
begin
WriteLn('Temp = ' + GetEnvironmentVariable('TEMP'));
WriteLn('Temp = ' + GetEnvironmentVariable('TEMP'));
end.</lang>
end.</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==

{{works with|E-on-Java}}
{{works with|E-on-Java}}
<syntaxhighlight lang="e"><unsafe:java.lang.System>.getenv("HOME")</syntaxhighlight>

<lang e><unsafe:java.lang.System>.getenv("HOME")</lang>


=={{header|Eiffel}}==
=={{header|Eiffel}}==

The feature <code lang="eiffel">get</code> returns the value of an environment variable. <code lang="eiffel">get</code> is defined in the library class EXECUTION_ENVIRONMENT. So the class APPLICATION inherits from EXECUTION_ENVIRONMENT in order to make <code lang="eiffel">get</code> available.
The feature <code lang="eiffel">get</code> returns the value of an environment variable. <code lang="eiffel">get</code> is defined in the library class EXECUTION_ENVIRONMENT. So the class APPLICATION inherits from EXECUTION_ENVIRONMENT in order to make <code lang="eiffel">get</code> available.
<syntaxhighlight lang="eiffel ">class

<lang eiffel >class
APPLICATION
APPLICATION
inherit
inherit
Line 178: Line 342:
print (get ("USERNAME"))
print (get ("USERNAME"))
end
end
end</lang>
end</syntaxhighlight>

=={{header|Elixir}}==
<syntaxhighlight lang="elixir">System.get_env("PATH")</syntaxhighlight>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(getenv "HOME")</syntaxhighlight>


=={{header|EMal}}==
<lang lisp>(getenv "HOME")</lang>
<syntaxhighlight lang="emal">
fun showVariable = <text variable|writeLine(variable + ": '" + Runtime.get(variable) + "'")
showVariable("SystemDrive")
showVariable("USERNAME")
# we can get the environment variables as a map
Map variables = Runtime.variables()
writeLine(variables["TEMP"])
</syntaxhighlight>
{{Out}}
<pre>
SystemDrive: 'C:'
USERNAME: 'XXXYYY'
C:\Users\xxxyyy\AppData\Local\Temp
</pre>

=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
os:getenv( "HOME" ).
</syntaxhighlight>


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>puts(1,getenv("PATH"))</lang>
<syntaxhighlight lang="euphoria">puts(1,getenv("PATH"))</syntaxhighlight>

=={{header|F_Sharp|F#}}==
<syntaxhighlight lang="fsharp">open System

[<EntryPoint>]
let main args =
printfn "%A" (Environment.GetEnvironmentVariable("PATH"))
0</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>"HOME" os-env print</lang>
<syntaxhighlight lang="factor">"HOME" os-env print</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
{{works with|GNU Forth}}
{{works with|GNU Forth}}
<lang forth>s" HOME" getenv type</lang>
<syntaxhighlight lang="forth">s" HOME" getenv type</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|any Fortran compiler}}
{{works with|any Fortran compiler}}
<lang fortran>
<syntaxhighlight lang="fortran">program show_home
program show_home
implicit none
implicit none
character(len=32) :: home_val ! The string value of the variable HOME
character(len=32) :: home_val ! The string value of the variable HOME
Line 211: Line 405:
write(*,'(a)') 'No HOME to go to!'
write(*,'(a)') 'No HOME to go to!'
end if
end if
end program show_home
end program show_home</syntaxhighlight>

</lang>
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64

Var v = Environ("SystemRoot")
Print v
Sleep</syntaxhighlight>

{{out}}
<pre>
C:\WINDOWS
</pre>

=={{header|Frink}}==

<syntaxhighlight lang="funl">callJava["java.lang.System", "getenv", ["HOME"]]</syntaxhighlight>

{{out}}
<pre>
/home/frink
</pre>

=={{header|FunL}}==
<syntaxhighlight lang="funl">println( System.getenv('PATH') )
println( $home )
println( $user )</syntaxhighlight>

=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"

NSLog(@"%@",fn NSUserName)
NSLog(@"%@",fn NSFullUserName)
NSLog(@"%@",fn NSHomeDirectory)
NSLog(@"%@",fn NSTemporaryDirectory)

HandleEvents
</syntaxhighlight>

=={{header|Go}}==
=={{header|Go}}==
'''Simply:'''
;Simply:
<syntaxhighlight lang="go">package main
<lang go>
package main


import (
import (
Line 225: Line 456:
func main() {
func main() {
fmt.Println(os.Getenv("SHELL"))
fmt.Println(os.Getenv("SHELL"))
}</lang>
}</syntaxhighlight>
{{out}}
Output:
<pre>
<pre>
/bin/bash
/bin/bash
</pre>
</pre>
'''Alternatively:'''
;Alternatively:
Library function os.Environ returns all environment variables.

Library function os.Environ returns all environment variables. You're on your own then to parse out the one you want. Example:
You're on your own then to parse out the one you want.
Example:
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 251: Line 483:
}
}
fmt.Println(s, "not found")
fmt.Println(s, "not found")
}</lang>
}</syntaxhighlight>
{{out}}
Output:
<pre>
<pre>
SHELL has value /bin/bash
SHELL has value /bin/bash
</pre>
</pre>

=={{header|Gri}}==
Command <code>get env</code> fetches an environment variable into a synonym (a string)
<syntaxhighlight lang="gri">get env \foo HOME
show "\foo"</syntaxhighlight>

Quotes can be used in the usual way if the environment variable name contains spaces (which is unusual, but possible).
<syntaxhighlight lang="gri">get env \foo "X Y Z"</syntaxhighlight>

=={{header|Groovy}}==
<syntaxhighlight lang="groovy">System.getenv().each { property, value -> println "$property = $value"}</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>import System.Environment
<syntaxhighlight lang="haskell">import System.Environment
main = do getEnv "HOME" >>= print -- get env var
main = do getEnv "HOME" >>= print -- get env var
getEnvironment >>= print -- get the entire environment as a list of (key, value) pairs</lang>
getEnvironment >>= print -- get the entire environment as a list of (key, value) pairs</syntaxhighlight>

=={{header|hexiscript}}==
<syntaxhighlight lang="hexiscript">println env "HOME"
println env "PATH"
println env "USER"</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang HicEst>CHARACTER string*255
<syntaxhighlight lang="hicest">CHARACTER string*255


string = "PATH="
string = "PATH="
SYSTEM(GEteNV = string)</lang>
SYSTEM(GEteNV = string)</syntaxhighlight>

=={{header|i}}==
<syntaxhighlight lang="i">software {
print(load("$HOME"))
print(load("$USER"))
print(load("$PATH"))
}</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
{{works with|Unicon}}
{{works with|Unicon}}
<lang Icon>procedure main(arglist)
<syntaxhighlight lang="icon">procedure main(arglist)


if *envars = 0 then envars := ["HOME", "TRACE", "BLKSIZE","STRSIZE","COEXPSIZE","MSTKSIZE", "IPATH","LPATH","NOERRBUF"]
if *envars = 0 then envars := ["HOME", "TRACE", "BLKSIZE","STRSIZE","COEXPSIZE","MSTKSIZE", "IPATH","LPATH","NOERRBUF"]
Line 276: Line 531:
every v := !sort(envars) do
every v := !sort(envars) do
write(v," = ",image(getenv(v))|"* not set *")
write(v," = ",image(getenv(v))|"* not set *")
end</lang>
end</syntaxhighlight>


=={{header|J}}==
=={{header|J}}==
<lang j>2!:5'HOME'</lang>
<syntaxhighlight lang="j">2!:5'HOME'</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java>System.getenv("HOME") // get env var
<syntaxhighlight lang="java">System.getenv("HOME") // get env var
System.getenv() // get the entire environment as a Map of keys to values</lang>
System.getenv() // get the entire environment as a Map of keys to values</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
The JavaScript language has no facilities to access the computer: it relies on the host environment to provide it.
The JavaScript language has no facilities to access the computer: it relies on the host environment to provide it.

{{works with|JScript}}
{{works with|JScript}}
<lang javascript>var shell = new ActiveXObject("WScript.Shell");
<syntaxhighlight lang="javascript">var shell = new ActiveXObject("WScript.Shell");
var env = shell.Environment("PROCESS");
var env = shell.Environment("PROCESS");
WScript.echo('SYSTEMROOT=' + env.item('SYSTEMROOT'));</lang>
WScript.echo('SYSTEMROOT=' + env.item('SYSTEMROOT'));</syntaxhighlight>


=={{header|Joy}}==
=={{header|Joy}}==
<lang joy>"HOME" getenv.</lang>
<syntaxhighlight lang="joy">"HOME" getenv.</syntaxhighlight>

=={{header|jq}}==
<syntaxhighlight lang="jq">env.HOME</syntaxhighlight>If the environment variable name has spaces or special characters, the name must be given as a string, e.g. <tt>env."HOME"</tt>.

=={{header|jsish}}==
The Jsi ''Util'' module provides access to set ''Util.setenv(name, value)'' and get ''Util.getenv(name)'' process environment variables. ''Util.getenv()'', with no argument will return an object with all available name:value pairs.
<syntaxhighlight lang="javascript">/* Environment variables, in Jsi */
puts(Util.getenv("HOME"));
var environment = Util.getenv();
puts(environment.PATH);</syntaxhighlight>

=={{header|Julia}}==
{{works with|Julia|0.6}}

<syntaxhighlight lang="julia">@show ENV["PATH"]
@show ENV["HOME"]
@show ENV["USER"]</syntaxhighlight>

=={{header|K}}==
<syntaxhighlight lang="k">_getenv "HOME"</syntaxhighlight>

=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.0.6

// tested on Windows 10

fun main(args: Array<String>) {
println(System.getenv("SystemRoot"))
}</syntaxhighlight>

{{out}}
<pre>
C:\WINDOWS
</pre>

=={{header|langur}}==
<syntaxhighlight lang="langur">
writeln "HOME: ", _env'HOME
writeln "PATH: ", _env'PATH
writeln "USER: ", _env'USER
</syntaxhighlight>

=={{header|Lasso}}==
<syntaxhighlight lang="lasso">#!/usr/bin/lasso9

define getenv(sysvar::string) => {
local(regexp = regexp(
-find = `(?m)^` + #sysvar + `=(.*?)$`,
-input = sys_environ -> join('\n'),
-ignorecase
))
return #regexp ->find ? #regexp -> matchString(1)
}

stdoutnl(getenv('HOME'))
stdoutnl(getenv('PATH'))
stdoutnl(getenv('USER'))
stdoutnl(getenv('WHAT'))</syntaxhighlight>
{{out}}
<pre>/Users/rosetta
/opt/local/bin:/opt/local/sbin:/usr/local/bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin
rosetta
</pre>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
=== Built-in variables ===
=== Built-in variables ===
<lang lb>print StartupDir$
<syntaxhighlight lang="lb">print StartupDir$
print DefaultDir$</lang>
print DefaultDir$</syntaxhighlight>

=== Other variables ===
=== Other variables ===
<lang lb>print GetEnvironmentVariable$("USERNAME")
<syntaxhighlight lang="lb">print GetEnvironmentVariable$("USERNAME")
print GetEnvironmentVariable$("USERPROFILE") ' equivalent to UNIX HOME variable
print GetEnvironmentVariable$("USERPROFILE") ' equivalent to UNIX HOME variable
print GetEnvironmentVariable$("PATH")
print GetEnvironmentVariable$("PATH")
Line 330: Line 646:
GetEnvironmentVariable$ = left$(lpBuffer$, result)
GetEnvironmentVariable$ = left$(lpBuffer$, result)
end select
end select
end function</lang>
end function</syntaxhighlight>

=={{header|LIL}}==
LIL does not ship with a command to retrieve process environment variables. The '''system''' command could be used, but here is an extension in C for the lil shell.

<syntaxhighlight lang="c">
static LILCALLBACK lil_value_t fnc_env(lil_t lil, size_t argc, lil_value_t* argv)
{
if (!argc) return NULL;
return lil_alloc_string(getenv(lil_to_string(argv[0])));
}</syntaxhighlight>

Then inside the main functions for repl and nonint (Interactive, Noninteractive):
<syntaxhighlight lang="c">lil_register(lil, "env", fnc_env);</syntaxhighlight>

Now lil can get at the environment. That could fairly easily be extended further to return the entire environment array if no arguments are passed to '''env''', this just returns an empty result for that case. Defaults values could also be supported if the named environment variable is empty. Etcetera. Setting variables would be similar, a few lines of lil C to wrap a call to libc setenv in a new command, and registering the command.

{{out}}
<pre>prompt$ make
cc -c -g3 -std=c99 -pedantic -Wall -Wextra -Wno-format -Wno-long-long -Wno-unused-parameter main.c -o main.o
cc -g -L. -o lil main.o -llil -lm

prompt$ lil
Little Interpreted Language Interactive Shell
# env TERM
xterm-256color</pre>

=={{header|Lingo}}==
{{libheader|Shell Xtra}}
<syntaxhighlight lang="lingo">sx = xtra("Shell").new()
if the platform contains "win" then
path = sx.shell_cmd("echo %PATH%").line[1]
else
path = sx.shell_cmd("echo $PATH").line[1]
end if</syntaxhighlight>

=={{header|Logtalk}}==
Using the standard library:
<syntaxhighlight lang="logtalk">os::environment_variable('PATH', Path).</syntaxhighlight>

=={{header|LSL}}==
Rez a box on the ground, and add the following as a New Script.
<syntaxhighlight lang="lsl">default {
state_entry() {
llOwnerSay("llGetTimestamp()="+(string)llGetTimestamp());
llOwnerSay("llGetEnergy()="+(string)llGetEnergy());
llOwnerSay("llGetFreeMemory()="+(string)llGetFreeMemory());
llOwnerSay("llGetMemoryLimit()="+(string)llGetMemoryLimit());
}
}</syntaxhighlight>
{{out}}
<pre>llGetTimestamp()=2012-07-18T01:26:12.133137Z
llGetEnergy()=1.230000
llGetFreeMemory()=16000
llGetMemoryLimit()=65536</pre>

=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>print( os.getenv( "PATH" ) )</lang>
<syntaxhighlight lang="lua">print( os.getenv( "PATH" ) )</syntaxhighlight>

=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
\\ using read only variablles
Print "Platform: ";Platform$
Print "Computer Os: "; Os$
Print "Type of OS: ";OsBit;" bit"
Print "Computer Name:"; Computer$
Print "User Name: "; User.Name$
\\ using WScript.Shell
Declare objShell "WScript.Shell"
With objShell, "Environment" set env ("Process")
With env, "item" as Env$()
Print Env$("PATH")
Print Env$("HOMEPATH")
Declare objShell Nothing
\\ using internal Information object
Declare OsInfo INFORMATION
With OsInfo, "build" as build, "NtDllVersion" as NtDllVersion$
Method OsInfo, "GetCurrentProcessSID" as PID$
Method OsInfo, "IsProcessElevated" as isElevated
Print "Os build number: ";build
Print "Nr Dll version: ";NtDllVersion$
Print "ProcessSID: ";pid$
Print "Is Process Eleveted: ";isElevated
Declare OsInfo Nothing
}
Checkit
</syntaxhighlight>

=={{header|Make}}==
Make variables are initialized from the environment, so simply
<syntaxhighlight lang="make">TARGET = $(HOME)/some/thing.txt
foo:
echo $(TARGET)</syntaxhighlight>

The shell code in a rule can use the shell's environment in the usual way ([[Environment variables#Unix Shell|Unix Shell]]), but remember <code>$</code> must be doubled <code>$$</code> to get a literal <code>$</code> in that code.
<syntaxhighlight lang="make">bar:
echo "$$HOME"</syntaxhighlight>

If you mistakenly write just <code>$HOME</code> then it means the makefile <code>$H</code> followed by characters <code>OME</code>.

<syntaxhighlight lang="make">H = oops ...
bar:
echo $HOME

# prints oops ... OME</syntaxhighlight>

=={{header|Maple}}==
<syntaxhighlight lang="maple">getenv("PATH");</syntaxhighlight>

=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Environment["PATH"]</syntaxhighlight>

=={{header|MATLAB}} / {{header|Octave}}==
<syntaxhighlight lang="matlab"> getenv('HOME')
getenv('PATH')
getenv('USER')</syntaxhighlight>

=={{header|Mercury}}==
<syntaxhighlight lang="mercury">:- module env_var.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module maybe, string.

main(!IO) :-
io.get_environment_var("HOME", MaybeValue, !IO),
(
MaybeValue = yes(Value),
io.write_string("HOME is " ++ Value ++ "\n", !IO)
;
MaybeValue = no,
io.write_string("environment variable HOME not set\n", !IO)
).</syntaxhighlight>

=={{header|min}}==
{{works with|min|0.19.3}}
<syntaxhighlight lang="min">$PATH</syntaxhighlight>

=={{header|Modula-3}}==
<syntaxhighlight lang="modula3">MODULE EnvVars EXPORTS Main;

IMPORT IO, Env;

VAR
k, v: TEXT;

BEGIN
IO.Put(Env.Get("HOME") & "\n");


FOR i := 0 TO Env.Count - 1 DO
=={{header|Mathematica}}==
Env.GetNth(i, k, v);
<lang Mathematica>Environment["PATH"]</lang>
IO.Put(k & " = " & v & "\n")
END
END EnvVars.</syntaxhighlight>


=={{header|MUMPS}}==
=={{header|MUMPS}}==
<p>ANSI MUMPS doesn't allow access to the operating system except possibly through the View command and $View function, both of which are implementation specific. Intersystems' Caché does allow you to create processes with the $ZF function, and if the permissions for the Caché process allow it you can perform operating system commands.</p>
ANSI MUMPS doesn't allow access to the operating system except possibly through the View command and $View function, both of which are implementation specific. Intersystems' Caché does allow you to create processes with the $ZF function, and if the permissions for the Caché process allow it you can perform operating system commands.
<p>In Caché on OpenVMS in an FILES-11 filesystem ODS-5 mode these could work:</p>
<lang MUMPS> Set X=$ZF(-1,"show logical")
Set X=$ZF(-1,"show symbol")</lang>


In Caché on OpenVMS in an FILES-11 filesystem ODS-5 mode these could work:
<syntaxhighlight lang="mumps"> Set X=$ZF(-1,"show logical")
Set X=$ZF(-1,"show symbol")</syntaxhighlight>

=={{header|NetRexx}}==
When NetRexx runs under a JVM, system ENVIRONMENT variables are complimented by JVM system properties. This sample shows how to get both.
<syntaxhighlight lang="netrexx">/* NetRexx */
options replace format comments java crossref symbols nobinary

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method sysEnvironment(vn = '') public static
if vn.length > 0 then do
envName = vn
envValu = System.getenv(envName)
if envValu = null then envValu = ''
say envName '=' envValu
end
else do
envVars = System.getenv()
key = String
loop key over envVars.keySet()
envName = key
envValu = String envVars.get(key)
say envName '=' envValu
end key
end
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method sysProperties(vn = '') public static
if vn.length > 0 then do
propName = vn
propValu = System.getProperty(propName)
if propValu = null then propValu = ''
say propName '=' propValu
end
else do
sysProps = System.getProperties()
key = String
loop key over sysProps.keySet()
propName = key
propValu = sysProps.getProperty(key)
say propName '=' propValu
end key
end
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static
parse arg ev pv .
if ev = '' then ev = 'CLASSPATH'
if pv = '' then pv = 'java.class.path'
say '-'.left(80, '-').overlay(' Environment "'ev'" ', 5)
sysEnvironment(ev)
say '-'.left(80, '-').overlay(' Properties "'pv'" ', 5)
sysProperties(pv)
say
say '-'.left(80, '-').overlay(' Environment ', 5)
sysEnvironment()
say '-'.left(80, '-').overlay(' Properties ', 5)
sysProperties()
say
return
</syntaxhighlight>
{{out}}
<pre>
---- Environment "CLASSPATH" ---------------------------------------------------
CLASSPATH = /usr/local/NetRexx/runlib/NetRexxR.jar:.
---- Properties "java.class.path" ----------------------------------------------
java.class.path = /usr/local/NetRexx/runlib/NetRexxR.jar:.

---- Environment ---------------------------------------------------------------
HOME = /Users/nrxuser
HISTCONTROL = ignoredups
USER = nrxuser
ZBASHRC = 1
COMMAND_MODE = unix2003
CLASSPATH = /usr/local/NetRexx/runlib/NetRexxR.jar:.
SHELL = /bin/bash
. . .
---- Properties ----------------------------------------------------------------
java.vm.specification.name = Java Virtual Machine Specification
sun.cpu.endian = little
sun.io.unicode.encoding = UnicodeBig
sun.os.patch.level = unknown
file.separator = /
java.vendor = Oracle Corporation
sun.java.launcher = SUN_STANDARD
java.specification.vendor = Oracle Corporation
user.home = /Users/nrxuser
java.class.path = /usr/local/NetRexx/runlib/NetRexxR.jar:.
java.vm.vendor = Oracle Corporation
java.runtime.name = Java(TM) SE Runtime Environment
. . .
</pre>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>> (env "SHELL")
<syntaxhighlight lang="newlisp">> (env "SHELL")
"/bin/zsh"
"/bin/zsh"
> (env "TERM")
> (env "TERM")
"xterm"
"xterm"</syntaxhighlight>
</lang>


=={{header|NSIS}}==
=={{header|Nim}}==
<syntaxhighlight lang="nim">import os
echo getEnv("HOME")</syntaxhighlight>


=={{header|NSIS}}==
While common environment variables exist as constants within the NSIS script compilation environment [http://nsis.sourceforge.net/Docs/Chapter4.html#4.2.3 (see NSIS documentation)], arbitrarily-named environment variables' values may be retrieved using [http://nsis.sourceforge.net/Docs/Chapter4.html#4.9.2.7 '''ExpandEnvStrings'''].
While common environment variables exist as constants within the NSIS script compilation environment [http://nsis.sourceforge.net/Docs/Chapter4.html#4.2.3 (see NSIS documentation)], arbitrarily-named environment variables' values may be retrieved using [http://nsis.sourceforge.net/Docs/Chapter4.html#4.9.2.7 '''ExpandEnvStrings'''].
<lang nsis>ExpandEnvStrings $0 "%PATH%" ; Retrieve PATH and place it in builtin register 0.
<syntaxhighlight lang="nsis">ExpandEnvStrings $0 "%PATH%" ; Retrieve PATH and place it in builtin register 0.
ExpandEnvStrings $1 "%USERPROFILE%" ; Retrieve the user's profile location and place it in builtin register 1.
ExpandEnvStrings $1 "%USERPROFILE%" ; Retrieve the user's profile location and place it in builtin register 1.
ExpandEnvStrings $2 "%USERNAME%" ; Retrieve the user's account name and place it in builtin register 2.</lang>
ExpandEnvStrings $2 "%USERNAME%" ; Retrieve the user's account name and place it in builtin register 2.</syntaxhighlight>

=={{header|Nu}}==
<syntaxhighlight lang="nu">
$env.HOME
</syntaxhighlight>


=={{header|Objective-C}}==
=={{header|Objective-C}}==
<code>[[NSProcessInfo processInfo] environment]</code> returns an <tt>NSDictionary</tt> of the current environment.
<code>[[NSProcessInfo processInfo] environment]</code> returns an <tt>NSDictionary</tt> of the current environment.
<lang objc>[[[NSProcessInfo processInfo] environment] objectForKey:@"HOME"]</lang>
<syntaxhighlight lang="objc">[[[NSProcessInfo processInfo] environment] objectForKey:@"HOME"]</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>Sys.getenv "HOME"</lang>
<syntaxhighlight lang="ocaml">Sys.getenv "HOME"</syntaxhighlight>

=={{header|Oforth}}==

<syntaxhighlight lang="oforth">System getEnv("PATH") println</syntaxhighlight>


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>{System.showInfo "This is where Mozart is installed: "#{OS.getEnv 'OZHOME'}}</lang>
<syntaxhighlight lang="oz">{System.showInfo "This is where Mozart is installed: "#{OS.getEnv 'OZHOME'}}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.6.0 and above}}
{{incorrect|This shows that the environment vector can pass through to a child process, which is an operating system feature.}}
<lang parigp>system("echo $HOME")</lang>
<syntaxhighlight lang="parigp">getenv("HOME")</syntaxhighlight>
{{works with|PARI/GP|2.4.3 and above}}
<syntaxhighlight lang="parigp">externstr("echo $HOME")</syntaxhighlight>
{{works with|PARI/GP|2.0.3 and above}}
In older versions, the command must effectively be triple-quoted:
<syntaxhighlight lang="parigp">extern("echo \"\\\"$HOME\\\"\"")</syntaxhighlight>
The shell sees
<syntaxhighlight lang="bash">echo "\"$HOME\""</syntaxhighlight>
which causes it to return
<pre>"/home/username"</pre>
so that the result is interpreted by GP as a string.


Leaving out the quotation marks allows external commands to return expressions that are then evaluated by GP. For example,
=={{header|Pascal}}==
<syntaxhighlight lang="parigp">extern("echo Pi")</syntaxhighlight>
See [[Environment_variables#Delphi | Delphi]]
causes the shell to send Pi back to GP, which interprets the result and returns
<pre>%1 = 3.141592653589793238462643383</pre>


=={{header|Perl}}==
=={{header|Perl}}==
The <code>%ENV</code> hash maps environment variables to their values:
The <code>%ENV</code> hash maps environment variables to their values:
<lang perl>print $ENV{HOME}, "\n";</lang>
<syntaxhighlight lang="perl">print $ENV{HOME}, "\n";</syntaxhighlight>


The <code>POSIX</code>module also has <code>getenv()</code> which is the same thing as a function.
=={{header|Perl 6}}==
<syntaxhighlight lang="perl">use POSIX 'getenv';
{{works with|Rakudo|#24 "Seoul"}}
print getenv("HOME"),"\n";</syntaxhighlight>


=={{header|Phix}}==
The <code>%*ENV</code> hash maps environment variables to their values:
<!--<syntaxhighlight lang="phix">(notonline)-->
<lang perl6>say %*ENV<HOME>;</lang>
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- none such in a browser, that I know of</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">getenv</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"PATH"</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->

=={{header|Phixmonti}}==
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Environment_variables
by Galileo, 10/2022 #/

def getenv
" > output.txt" chain cmd if "Error!" else "output.txt" "r" fopen dup fgets swap fclose endif
enddef

"path" getenv print</syntaxhighlight>


=={{header|PHP}}==
=={{header|PHP}}==
The <tt>$_ENV</tt> associative array maps environmental variable names to their values:
The <tt>$_ENV</tt> associative array maps environmental variable names to their values:
<lang php>$_ENV['HOME']</lang>
<syntaxhighlight lang="php">$_ENV['HOME']</syntaxhighlight>


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>: (sys "TERM")
<syntaxhighlight lang="picolisp">: (sys "TERM")
-> "xterm"
-> "xterm"


: (sys "SHELL")
: (sys "SHELL")
-> "/bin/bash"</lang>
-> "/bin/bash"</syntaxhighlight>

=={{header|Pike}}==
<syntaxhighlight lang="pike">write("%s\n", getenv("SHELL"));</syntaxhighlight>
{{Out}}
<pre>
/bin/bash
</pre>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
Environment variables can be found in the Env: drive and are accessed using a special variable syntax:
Environment variables can be found in the Env: drive and are accessed using a special variable syntax:
<lang powershell>$Env:Path</lang>
<syntaxhighlight lang="powershell">$Env:Path</syntaxhighlight>
To get a complete listing of all environment variables one can simply query the appropriate drive for its contents:
To get a complete listing of all environment variables one can simply query the appropriate drive for its contents:
<lang powershell>Get-ChildItem Env:</lang>
<syntaxhighlight lang="powershell">Get-ChildItem Env:</syntaxhighlight>

=={{header|Prolog}}==
SWI-Prolog has the built in function '''getenv'''.
<pre> ?- getenv('TEMP', Temp).
</pre>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
PureBasic has the built in funtion
PureBasic has the built in funtion
<lang PureBasic>GetEnvironmentVariable("Name")</lang>
<syntaxhighlight lang="purebasic">GetEnvironmentVariable("Name")</syntaxhighlight>


'''Example'''
'''Example'''
<lang PureBasic>If OpenConsole()
<syntaxhighlight lang="purebasic">If OpenConsole()
PrintN("Path:"+#CRLF$ + GetEnvironmentVariable("PATH"))
PrintN("Path:"+#CRLF$ + GetEnvironmentVariable("PATH"))
PrintN(#CRLF$+#CRLF$+"NUMBER_OF_PROCESSORS= "+ GetEnvironmentVariable("NUMBER_OF_PROCESSORS"))
PrintN(#CRLF$+#CRLF$+"NUMBER_OF_PROCESSORS= "+ GetEnvironmentVariable("NUMBER_OF_PROCESSORS"))
Line 415: Line 1,025:
Input()
Input()
CloseConsole()
CloseConsole()
EndIf</lang>
EndIf</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
The <tt>os.environ</tt> dictionary maps environmental variable names to their values:
The <tt>os.environ</tt> dictionary maps environmental variable names to their values:
<lang python>import os
<syntaxhighlight lang="python">import os
os.environ['HOME']</lang>
os.environ['HOME']</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
<lang R>Sys.getenv("PATH")</lang>
<syntaxhighlight lang="r">Sys.getenv("PATH")</syntaxhighlight>

=={{header|Racket}}==
<syntaxhighlight lang="racket">
#lang racket
(getenv "HOME")
</syntaxhighlight>

=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|#24 "Seoul"}}
The <code>%*ENV</code> hash maps environment variables to their values:
<syntaxhighlight lang="raku" line>say %*ENV<HOME>;</syntaxhighlight>


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang REBOL>print get-env "HOME"</lang>
<syntaxhighlight lang="rebol">print get-env "HOME"</syntaxhighlight>


=={{header|Retro}}==
=={{header|Retro}}==
<lang Retro>here "HOME" getEnv
<syntaxhighlight lang="retro">here "HOME" getEnv
here puts</lang>
here puts</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Each REXX interpreter sets its own rules by what identifies the pool in which the environmental variables are named. In addition, each operation system (OS) has their own definition as well. This makes it problematic in the accessing/acquiring of environmental variables. Most programmers know what REXX interpreter they are using, and furthermore, they also know what operating system they are writing the REXX program for, so most programmers hard-wire (explicitly code) the "access-name" of the system environmental variables into the program.
Each REXX interpreter sets its own rules by what identify the environmental variables are named.
<br>In addition, each operation system (OS) hase their own definition as well.
<br>This makes it problamatic in the acessing/acquiring of environmental variables.
<br>Most programmers know what REXX interpreter they are using, and furthermore, they also
<br>know what operating system they are writing the REXX program for, so most programmers hard-wire
<br>(explicitly code) the "access-name" of the system environmental variables into the program.
<br><br>The following will work for Regina and R4 for the DOS shell under Windows (any version).
<lang rexx>
/*REXX program shows how to get an environmental variable under Windows*/


The following will work for
x=value('TEMP',,'SYSTEM')
::* '''Regina'''
</lang>
::* '''R4'''
The following will work for PC/REXX and Regina for the DOS shell under Windows (any version).
::* '''ROO'''
<lang rexx>
for the DOS shell under Microsoft Windows (any version).<br />
/*REXX program shows how to get an environmental variable under Windows*/
(Also successfully tested with Regina under the bash shell in UNIX.)
{{works with|Regina}}
{{works with|R4}}
{{works with|ROO}}
<syntaxhighlight lang="rexx">/*REXX program shows how to get an environmental variable under Windows*/


x=value('TEMP',,'ENVIRONMENT')
x=value('TEMP',,'SYSTEM')</syntaxhighlight>
The following will work for
</lang>
::* '''PC/REXX'''
Other REXX interpreters have their own requirements to identify the SYSTEM environment.
::* '''Personal REXX'''
::* '''Regina'''
::* '''Open Object Rexx'''
for the DOS shell under Microsoft Windows (any version).<br />
(Also successfully tested with Regina and ooRexx under the bash shell in UNIX.)
{{works with|PC/REXX}}
{{works with|Personal REXX}}
{{works with|Regina}}
{{works with|ooRexx}}
<syntaxhighlight lang="rexx">/*REXX program shows how to get an environmental variable under Windows*/

x=value('TEMP',,'ENVIRONMENT')</syntaxhighlight>

The brexx interpreter provides a getenv function for accessing environment variables:
{{works with|Brexx}}
<syntaxhighlight lang="rexx">x=getenv("PATH") /* Get the contents of the path environment variable */</syntaxhighlight>

Other REXX interpreters have their own requirements to identify the SYSTEM environment.
<br>VM/CMS has something called GLOBALV (global variables) and are of three types:
<br>VM/CMS has something called GLOBALV (global variables) and are of three types:
<br>* temporary (lasting only for execution of the REXX program),
::* temporary, &nbsp; lasting only for execution of the REXX program
<br>* temporary (lasting only for LOGON or CMS session),
::* temporary, &nbsp; lasting only for LOGON or CMS session)
<br>* permanent.
::* permanent
<br><br>As such, CMS has its own command interface for these variables.
As such, CMS has its own command interface for these variables.

=={{header|Ring}}==
<syntaxhighlight lang="ring">
see get("path")
</syntaxhighlight>


=={{header|Ruby}}==
=={{header|Ruby}}==
The <tt>ENV</tt> hash maps environmental variable names to their values:
The <tt>ENV</tt> hash maps environment variable names to their values:
<lang ruby>ENV['HOME']</lang>
<syntaxhighlight lang="ruby">ENV['HOME']</syntaxhighlight>

=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">' ------- Major environment variables -------------------------------------------
'DefaultDir$ - The folder path where program files are read/written by default
'Platform$ - The operating system on which Run BASIC is being hosted
'UserInfo$ - This is information about the user's web browser
'UrlKeys$ - Contains informational parameters from the URL submitted when the user connected
'UserAddress$ - Contains the IP address of the user
'ProjectsRoot$ - The folder path where Run BASIC keeps programming projects
'ResourcesRoot$ - The folder path where Run BASIC keeps web-servable files
'Err$ - A description of the last runtime error
'Err - A numeric code for the last runtime error (errors that have no code use zero)
'EventKey$ - The id of the object that generated the last user event
'RowIndex - The numeric index of the table or database accessor link that generated the last user event


print "User Info is : ";UserInfo$
print "Platform is : ";Platform$
print "Url Keys is : ";UrlKeys$
print "User Address is: ";UserAddress$
print "Event Key is : ";EventKey$
print "Default Dir is : ";DefaultDir$</syntaxhighlight>
<pre>
{{out}}
User Info is : Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11
Platform is : win32
Url Keys is : none
User Address is: 127.0.0.1
Event Key is : none
Default Dir is : c:\rbp101
</pre>

=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::env;

fn main() {
println!("{:?}", env::var("HOME"));
println!();
for (k, v) in env::vars().filter(|(k, _)| k.starts_with('P')) {
println!("{}: {}", k, v);
}
}
</syntaxhighlight>
{{out}}
<pre>Ok("/root")

PATH: /root/.cargo/bin:/root/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PLAYGROUND_EDITION: 2018
PLAYGROUND_TIMEOUT: 10
PWD: /playground</pre>
Note that <code>var_os</code> and <code>vars_os</code> are also available, which produce <code>OsString</code> instead of <code>String</code>, offering compatibility with non-utf8 systems.

=={{header|Scala}}==
<syntaxhighlight lang="scala">sys.env.get("HOME")</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
Seed7 provides the function [http://seed7.sourceforge.net/manual/os.htm#getenv getenv],
<lang seed7>$ include "seed7_05.s7i";
to get the value of an environment variable. Environment variables are highly operating system
dependent. Some variables such as HOME are not always defined and others like PATH use
an operating system dependent format (different delimiters). Seed7 provides the functions
[http://seed7.sourceforge.net/libraries/osfiles.htm#homeDir homeDir] and [http://seed7.sourceforge.net/libraries/process.htm#getSearchPath getSearchPath]
to get the home directory and the search path in an operating system independent manner.

<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
const proc: main is func
const proc: main is func
begin
begin
writeln(getenv("HOME"));
writeln(getenv("HOME"));
end func;</lang>
end func;</syntaxhighlight>

=={{header|Sidef}}==
The ''ENV'' hash maps environment variables to their values:
<syntaxhighlight lang="ruby">say ENV{'HOME'};</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<syntaxhighlight lang="slate">Environment variables at: 'PATH'.
"==> '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'"</syntaxhighlight>
<lang slate>Environment variables at: 'PATH'.
"==> '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'"</lang>


=={{header|Standard ML}}==
=={{header|Slope}}==
<syntaxhighlight lang="slope">(env "HOME")</syntaxhighlight>
<lang sml>OS.Process.getEnv "HOME"</lang>

returns an option type which is either SOME value or NONE if variable doesn't exist
=={{header|Smalltalk}}==
Use the [http://pharo.gemtalksystems.com/book/PharoTools/OSProcess OSProcess] library to gain access to environment variables:

<syntaxhighlight lang="smalltalk">
OSProcess thisOSProcess environment at: #HOME.
OSProcess thisOSProcess environment at: #PATH.
OSProcess thisOSProcess environment at: #USER.
</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
{{works with|Macro Spitbol}}
{{works with|Macro Spitbol}}
{{works with|CSnobol}}
{{works with|CSnobol}}

The host(4) function returns a known environment variable.
The host(4) function returns a known environment variable.
<lang SNOBOL4> output = host(4,'PATH')
<syntaxhighlight lang="snobol4"> output = host(4,'PATH')
end</lang>
end</syntaxhighlight>

=={{header|Standard ML}}==
<syntaxhighlight lang="sml">OS.Process.getEnv "HOME"</syntaxhighlight>
returns an option type which is either SOME value or NONE if variable doesn't exist

=={{header|Stata}}==
Use the '''env''' [http://www.stata.com/help.cgi?extended_fcn extended macro function].

<syntaxhighlight lang="stata">display "`:env PATH'"
display "`:env USERNAME'"
display "`:env USERPROFILE'"</syntaxhighlight>

=={{header|Swift}}==

<syntaxhighlight lang="swift">print("USER: \(ProcessInfo.processInfo.environment["USER"] ?? "Not set")")
print("PATH: \(ProcessInfo.processInfo.environment["PATH"] ?? "Not set")")</syntaxhighlight>

=={{header|True BASIC}}==
<syntaxhighlight lang="qbasic">ASK #1: ACCESS type$
ASK BACK red
ASK COLOR red
ASK COLOR MIX (2) red, green, blue
ASK CURSOR vble1, vble2
ASK #2: DATUM type$
ASK DIRECTORY dir$
ASK #3: ERASABLE type$
ASK #4: FILESIZE vble09
ASK #5: FILETYPE vble10
ASK FREE MEMORY vble11
ASK #61: MARGIN vble12
ASK MAX COLOR vble13
ASK MAX CURSOR vble1, vble2
ASK MODE vble15$
ASK NAME vble16$
ASK #7: ORGANIZATION vble17$
ASK PIXELS vble1, vble2
ASK #8: POINTER vble19$
ASK #9: RECORD vble20
ASK #1: RECSIZE vble21
ASK #2: RECTYPE vble22$
ASK SCREEN vble1, vble2, vble3, vble4
ASK #3: SETTER vble24$
ASK TEXT JUSTIFY vble1$, vble2$
ASK WINDOW vble1, vble2, vble3, vble4
ASK #4: ZONEWIDTH vble27</syntaxhighlight>


=={{header|Tcl}}==
=={{header|Tcl}}==
The <code>env</code> global array maps environmental variable names to their values:
The <code>env</code> global array maps environmental variable names to their values:
<lang tcl>$env(HOME)</lang>
<syntaxhighlight lang="tcl">$env(HOME)</syntaxhighlight>


=={{header|TXR}}==
=={{header|TXR}}==

{{works with|TXR|"git head"}}

TXR can treat the environment vector as text stream:
TXR can treat the environment vector as text stream:
<syntaxhighlight lang="txr">@(next :env)

<lang txr>@(next :env)
@(collect)
@(collect)
@VAR=@VAL
@VAR=@VAL
@(end)</lang>
@(end)</syntaxhighlight>

A recently added <code>gather</code> directive is useful for extracting multiple items of data from an unordered stream of this kind (not only the environment vector):
A recently added <code>gather</code> directive is useful for extracting multiple items of data from an unordered stream of this kind (not only the environment vector):
<syntaxhighlight lang="txr">@(next :env)

<lang txr>@(next :env)
@(gather)
@(gather)
HOME=@home
HOME=@home
USER=@user
USER=@user
PATH=@path
PATH=@path
@(end)</lang>
@(end)</syntaxhighlight>

What if some of the variables might not exist? Gather has some discipline for that. The following means that three variables are required (the gather construct fails if they are not found), but <code>shell</code> is optional with a default value of <code>/bin/sh</code> if it is not extracted from the data:
What if some of the variables might not exist? Gather has some discipline for that. The following means that three variables are required (the gather construct fails if they are not found), but <code>shell</code> is optional with a default value of <code>/bin/sh</code> if it is not extracted from the data:
<syntaxhighlight lang="txr">@(next :env)

<lang txr>@(next :env)
@(gather :vars (home user path (shell "/bin/sh")))
@(gather :vars (home user path (shell "/bin/sh")))
HOME=@home
HOME=@home
Line 519: Line 1,269:
PATH=@path
PATH=@path
SHELL=@shell
SHELL=@shell
@(end)</lang>
@(end)</syntaxhighlight>
From TXR Lisp, the environment is available via the <code>(env)</code> function, which returns a raw list of <code>"name=value</code> strings. The <code>(env-hash)</code> function returns a hash from environment keys to their values.


<syntaxhighlight lang="bash">$ ./txr -p "(mapcar (env-hash) '(\"HOME\" \"USER\" \"PATH\"))"
On POSIX, environment variables, which are extracted using <code>extern char **environ</code> are assumed to contain UTF-8. On Windows, the <code>GetEnvironmentStringsW</code> function is used to obtain the environment vector as wide character data.
("/home/kaz" "kaz" "/home/kaz/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/kaz/bin"</syntaxhighlight>

Here, the hash is being used as a function to filter several environment keys to their values via <code>mapcar</code>.


Platform note: On POSIX, environment variables, which are extracted using <code>extern char **environ</code> are assumed to contain UTF-8. On Windows, the <code>GetEnvironmentStringsW</code> function is used to obtain the environment vector as wide character data.


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
In the Unix Shell Language, environment variables are available as ordinary variables:
In the Unix Shell Language, environment variables are available as ordinary variables:
<lang bash>echo $HOME</lang>
<syntaxhighlight lang="bash">echo "$HOME"</syntaxhighlight>
An ordinary variable can be marked as an environment variable with the <code>export</code> command:
An ordinary variable can be marked as an environment variable with the <code>export</code> command:
<lang bash>export VAR</lang>
<syntaxhighlight lang="bash">export VAR</syntaxhighlight>
Now child processes launched by the shell will have an environment variable called <code>VAR</code>.
Now child processes launched by the shell will have an environment variable called <code>VAR</code>.


The Unix command "env" will print out all of the environment variables as key=value pairs on standard output.
The Unix command "env" will print out all of the environment variables
as key=value pairs on standard output.

=={{header|Ursa}}==
<syntaxhighlight lang="ursa">import "system"
out (system.getenv "HOME") endl console</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
The argument to the main program is a record initialized by the run-time system in which one of the fields (environs) contains the environment as a list of key:value pairs.
The argument to the main program
<syntaxhighlight lang="ursala">#import std
is a record initialized by the run-time system in which one of
the fields (environs) contains the environment as a list of key:value pairs.
<lang Ursala>#import std


#executable ('parameterized','')
#executable ('parameterized','')


showenv = <.file$[contents: --<''>]>+ %smP+ ~&n-={'TERM','SHELL','X11BROWSER'}*~+ ~environs</lang>
showenv = <.file$[contents: --<''>]>+ %smP+ ~&n-={'TERM','SHELL','X11BROWSER'}*~+ ~environs</syntaxhighlight>
The rest of this application searches for the three variables named and displays them on standard output.
The rest of this application searches for the three variables named
and displays them on standard output.
Here is a bash session.

{{out|Here is a bash session}}
<pre>
<pre>
$ showenv
$ showenv
Line 550: Line 1,312:
'X11BROWSER': '/usr/bin/firefox'></pre>
'X11BROWSER': '/usr/bin/firefox'></pre>


=={{header|Vedit macro language}}==
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">// Environment variables in V
<lang vedit>Get_Environment(10,"PATH")
// v run environment_variables.v
Message(@10)</lang>
module main


import os

pub fn main() {
print('In the $os.environ().len environment variables, ')
println('\$HOME is set to ${os.getenv('HOME')}')
}</syntaxhighlight>

{{out}}<pre>prompt$ v run environment-variables.v
In the 64 environment variables, $HOME is set to /home/btiffin</pre>

=={{header|Vedit macro language}}==
<syntaxhighlight lang="vedit">Get_Environment(10,"PATH")
Message(@10)</syntaxhighlight>
Or with short keywords:
Or with short keywords:
<lang vedit>GE(10,"PATH") M(@10)</lang>
<syntaxhighlight lang="vedit">GE(10,"PATH") M(@10)</syntaxhighlight>


=={{header|Visual Basic}}==
{{omit from|TI-83 BASIC}} {{omit from|TI-89 BASIC}} <!-- Does not have an environment other than regular global variables. -->
{{works with|Visual Basic|VB6 Standard}}
{{omit from|M4}}
<syntaxhighlight lang="vb">Debug.Print Environ$("PATH")</syntaxhighlight>
{{omit from|Unlambda|Does not provide access to environment variables.}}

=={{header|Wren}}==
Wren CLI doesn't currently expose a way to obtain the value of an environment variable.

However, if Wren is embedded in (say) a suitable Go program, then we can ask the latter to obtain it for us.
<syntaxhighlight lang="wren">/* Environment_variables.wren */
class Environ {
foreign static variable(name)
}

System.print(Environ.variable("SHELL"))</syntaxhighlight>

which we embed in the following Go program and run it.
{{libheader|WrenGo}}
<syntaxhighlight lang="go">/* Environment_variables.go */
package main

import (
wren "github.com/crazyinfin8/WrenGo"
"os"
)

type any = interface{}

func getEnvironVariable(vm *wren.VM, parameters []any) (any, error) {
name := parameters[1].(string)
return os.Getenv(name), nil
}

func main() {
vm := wren.NewVM()
fileName := "Environment_variables.wren"
methodMap := wren.MethodMap{"static variable(_)": getEnvironVariable}
classMap := wren.ClassMap{"Environ": wren.NewClass(nil, nil, methodMap)}
module := wren.NewModule(classMap)
vm.SetModule(fileName, module)
vm.InterpretFile(fileName)
vm.Free()
}</syntaxhighlight>

{{out}}
<pre>
/bin/bash
</pre>

=={{header|XPL0}}==
This task was particularly worthwhile because it revealed a discrepancy
in the way 32-bit XPL0 accessed the environment block. A small mod to
Tran's PMODE.ASM DPMI was required to make the 32-bit protected-mode
version work the same as the 16-bit real-mode versions.

<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
string 0; \use zero-terminated strings
int CpuReg, PspSeg, EnvSeg, I, J, C;
char EnvVar;
[CpuReg:= GetReg; \access CPU registers
PspSeg:= CpuReg(9); \get segment address of our PSP
EnvSeg:= Peek(PspSeg,$2C) + Peek(PspSeg,$2D)<<8;
EnvVar:= "PATH"; \environment variable
I:= 0;
loop [J:= 0;
loop [C:= Peek(EnvSeg,I); I:= I+1;
if C = 0 then quit;
if C = EnvVar(J) then
[J:= J+1;
if J = 4 then
[Text(0, EnvVar); \show env. var.
loop [C:= Peek(EnvSeg,I); \ and rest of
I:= I+1; \ its string
if C = 0 then exit;
ChOut(0, C);
];
];
]
else J:= 5; \line must start with environment variable
];
if Peek(EnvSeg,I) = 0 then quit; \double 0 = env. var. not found
];
]</syntaxhighlight>

{{out}}
<pre>
PATH=\masm6;C:\;C:\CXPL;C:\UTIL;C:\DOS;C:\BORLANDC\BIN
</pre>

=={{header|Yabasic}}==
<code>peek$("env","NAME")</code> Return the environment variable specified by NAME (which may be any string expression).

Which kind of environment variables are available on your system depends, as well as their meaning, on your system; however typing env on the command line will produce a list (for Windows and Unix alike).


Note, that peek$("env",...) can be written as peek$("environment",...) too.


=={{header|zkl}}==
[[Category: Environment variables]]
<syntaxhighlight lang="zkl">System.getenv("HOME")
[[Category:Initialization]]
/home/craigd
System.getenv() //--> Dictionary of all env vars</syntaxhighlight>

Latest revision as of 13:50, 21 June 2024

Task
Environment variables
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Show how to get one of your process's environment variables.

The available variables vary by system;   some of the common ones available on Unix include:

  •   PATH
  •   HOME
  •   USER



11l

print(os:getenv(‘HOME’))

Ada

Print a single environment variable.

with Ada.Environment_Variables; use Ada.Environment_Variables;
with Ada.Text_Io; use Ada.Text_Io;

procedure Print_Path is
begin
   Put_Line("Path : " & Value("PATH"));
end Print_Path;

Print all environment variable names and values.

with Ada.Environment_Variables; use Ada.Environment_Variables;
with Ada.Text_Io; use Ada.Text_Io;

procedure Env_Vars is
   procedure Print_Vars(Name, Value : in String) is
   begin
      Put_Line(Name & " : " & Value);
   end Print_Vars;
begin
   Iterate(Print_Vars'access);
end Env_Vars;


Alternative version using Matreshka

Uses Matreshka.

with Ada.Wide_Wide_Text_IO;

with League.Application;
with League.Strings;

procedure Main is

   function "+"
    (Item : Wide_Wide_String) return League.Strings.Universal_String
       renames League.Strings.To_Universal_String;

begin
   Ada.Wide_Wide_Text_IO.Put_Line
    (League.Application.Environment.Value (+"HOME").To_Wide_Wide_String);
end Main;

ALGOL 68

Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386 - getenv is not part of the standard's prelude
print((getenv("HOME"), new line))

APL

      ⎕ENV 'HOME'
 HOME /home/russtopia

AppleScript

Invoking Finder

tell application "Finder" to get name of home

Invoking Terminal

"HOME : " & (do shell script "echo $HOME" & ", PATH : " & (do shell script "echo $PATH" & ", USER : " & (do shell script "echo $USER")))

Arturo

print ["path:" env\PATH]
print ["user:" env\USER]
print ["home:" env\HOME]
Output:
path: /Users/drkameleon/.arturo/bin:/opt/local/bin:/opt/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
user: drkameleon 
home: /Users/drkameleon

AutoHotkey

EnvGet, OutputVar, Path
MsgBox, %OutputVar%

AutoIt

ConsoleWrite("# Environment:" & @CRLF)

Local $sEnvVar = EnvGet("LANG")
ConsoleWrite("LANG : " & $sEnvVar & @CRLF)

ShowEnv("SystemDrive")
ShowEnv("USERNAME")

Func ShowEnv($N)
    ConsoleWrite( StringFormat("%-12s : %s\n", $N, EnvGet($N)) )
EndFunc   ;==>ShowEnv
Output:
# Environment:
LANG : DE
SystemDrive  : C:
USERNAME     : HaJo

AWK

The ENVIRON array contains the values of the current environment:

$ awk 'BEGIN{print "HOME:"ENVIRON["HOME"],"USER:"ENVIRON["USER"]}'
Output:
HOME:/home/suchrich USER:SuchRich

Environment variables can also be assigned to awk variables before execution, with (-v) options:

$ awk -v h=$HOME -v u=$USER 'BEGIN{print "HOME:"h,"USER:"u}'
Output:
HOME:/home/suchrich USER:SuchRich

Listing all the environment variables:

# http://ideone.com/St5SHF
BEGIN { print "# Environment:"
        for (e in ENVIRON) { printf( "%10s = %s\n", e, ENVIRON[e] ) }
}
END   { print "# Done." }
Output:
# Environment:
   AWKPATH = .:/usr/share/awk
AWKLIBPATH = /usr/lib/i386-linux-gnu/gawk
      LANG = en_US.UTF-8
      PATH = /usr/local/bin:/usr/bin:/bin
      HOME = /home/guest
       PWD = /home/guest
     SHLVL = 0
    TMPDIR = /home/guest
# Done.

BASIC

x$ = ENVIRON$("path")
PRINT x$

BaCon

Case matters and needs to match

PRINT GETENVIRON$("PATH")

IS-BASIC

100 ASK BORDER VAR01
110 ASK DEFAULT CHANNEL VAR02
120 ASK EDITOR BUFFER VAR03
130 ASK EDITOR KEY VAR04
140 ASK EDITOR VIDEO VAR05
150 ASK FAST SAVE VAR06
160 ASK INTERRUPT KEY VAR07
170 ASK INTERRUPT NET VAR08
180 ASK INTERRUPT STOP VAR09
190 ASK KEY CLICK VAR10
200 ASK KEY DELAY VAR11
210 ASK KEY RATE VAR12
220 ASK NET CHANNEL VAR13
230 ASK NET MACHINE VAR14
240 ASK REM1 VAR15
250 ASK REM2 VAR16
260 ASK SERIAL BAUD VAR17
270 ASK SERIAL FORMAT VAR18
280 ASK STATUS VAR19
290 ASK SOUND BUFFER VAR20
300 ASK SPEAKER VAR21
310 ASK TAPE LEVEL VAR22
320 ASK TAPE SOUND VAR23
330 ASK TIMER VAR24
340 ASK VIDEO COLOR VAR25
350 ASK VIDEO MODE VAR26
360 ASK VIDEO X VAR27
370 ASK VIDEO Y VAR28

or

ASK machine-option-code var

SmallBASIC

print env("HOME")
print env("PATH")
print env("USER")

ZX Spectrum Basic

The ZX Spectrum does not use environmental variables in a traditional sense. However, it does provide a set of system variables held at a fixed memory address:

10 PRINT "The border colour is "; PEEK (23624): REM bordcr
20 PRINT "The ramtop address is "; PEEK (23730) + 256 * PEEK (23731): REM ramtop
30 POKE 23609,50: REM set keyboard pip to 50

Batch File

Batch files don't have any other kind of variables except environment variables. They can be accessed by enclosing the variable name in percent signs:

echo %Foo%

For interactive use one can use set to view all environment variables or all variables starting with a certain string:

set
set Foo

BBC BASIC

      PRINT FNenvironment("PATH")
      PRINT FNenvironment("USERNAME")
      END
      
      DEF FNenvironment(envar$)
      LOCAL buffer%, size%
      SYS "GetEnvironmentVariable", envar$, 0, 0 TO size%
      DIM buffer% LOCAL size%
      SYS "GetEnvironmentVariable", envar$, buffer%, size%+1
      = $$buffer%

C

#include <stdlib.h>
#include <stdio.h>
 
int main() {
  puts(getenv("HOME"));
  puts(getenv("PATH"));
  puts(getenv("USER"));
  return 0;
}

C#

using System;

namespace RosettaCode {
    class Program {
        static void Main() {
            string temp = Environment.GetEnvironmentVariable("TEMP");
            Console.WriteLine("TEMP is " + temp);
        }
    }
}

C++

#include <cstdlib>
#include <cstdio>

int main()
{
   puts(getenv("HOME"));
   return 0;
}

Clojure

(System/getenv "HOME")

COBOL

       IDENTIFICATION DIVISION.
       PROGRAM-ID. Environment-Vars.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  home PIC X(75).

       PROCEDURE DIVISION.
*          *> Method 1.      
           ACCEPT home FROM ENVIRONMENT "HOME"
           DISPLAY home

*          *> Method 2.
           DISPLAY "HOME" UPON ENVIRONMENT-NAME
           ACCEPT home FROM ENVIRONMENT-VALUE

           GOBACK
           .

CoffeeScript

Works with: node.js
for var_name in ['PATH', 'HOME', 'LANG', 'USER']
  console.log var_name, process.env[var_name]

Common Lisp

Access to environment variables isn't a part of the Common Lisp standard, but most implementations provide some way to do it.

Works with: LispWorks
(lispworks:environment-variable "USER")
Works with: SBCL
(sb-ext:posix-getenv "USER")
Works with: Clozure CL
(ccl:getenv "USER")
Works with: CLISP
(getenv "HOME")

Ways to do this in some other implementations are listed in the Common Lisp Cookbook.

D

Library: phobos
import std.stdio, std.process;

void main() {
    auto home = getenv("HOME");
}
Library: tango
import tango.sys.Environment;

void main() {
    auto home = Environment("HOME");
}

Delphi/Pascal

program EnvironmentVariable;

{$APPTYPE CONSOLE}

uses SysUtils;

begin
  WriteLn('Temp = ' + GetEnvironmentVariable('TEMP'));
end.

E

Works with: E-on-Java
<unsafe:java.lang.System>.getenv("HOME")

Eiffel

The feature get returns the value of an environment variable. get is defined in the library class EXECUTION_ENVIRONMENT. So the class APPLICATION inherits from EXECUTION_ENVIRONMENT in order to make get available.

class
    APPLICATION
inherit
    EXECUTION_ENVIRONMENT
create
    make
feature {NONE} -- Initialization
    make
            -- Retrieve and print value for environment variable `USERNAME'.
        do
            print (get ("USERNAME"))
        end
end

Elixir

System.get_env("PATH")

Emacs Lisp

(getenv "HOME")

EMal

fun showVariable = <text variable|writeLine(variable + ": '"  + Runtime.get(variable) + "'")
showVariable("SystemDrive")
showVariable("USERNAME")
# we can get the environment variables as a map
Map variables = Runtime.variables()
writeLine(variables["TEMP"])
Output:
SystemDrive: 'C:'
USERNAME: 'XXXYYY'
C:\Users\xxxyyy\AppData\Local\Temp

Erlang

os:getenv( "HOME" ).

Euphoria

puts(1,getenv("PATH"))

F#

open System

[<EntryPoint>]
let main args =
    printfn "%A" (Environment.GetEnvironmentVariable("PATH"))
    0

Factor

"HOME" os-env print

Forth

Works with: GNU Forth
s" HOME" getenv type

Fortran

program show_home
implicit none
character(len=32) :: home_val  ! The string value of the variable HOME
integer           :: home_len  ! The actual length of the value
integer           :: stat      ! The status of the value:
                               !  0 = ok
                               !  1 = variable does not exist
                               ! -1 = variable is not long enought to hold the result
call get_environment_variable('HOME', home_val, home_len, stat)
if (stat == 0) then
    write(*,'(a)') 'HOME = '//trim(home_val)
else
    write(*,'(a)') 'No HOME to go to!'
end if
end program show_home

FreeBASIC

' FB 1.05.0 Win64

Var v = Environ("SystemRoot")
Print v
Sleep
Output:
C:\WINDOWS

Frink

callJava["java.lang.System", "getenv", ["HOME"]]
Output:
/home/frink

FunL

println( System.getenv('PATH') )
println( $home )
println( $user )

FutureBasic

include "NSLog.incl"

NSLog(@"%@",fn NSUserName)
NSLog(@"%@",fn NSFullUserName)
NSLog(@"%@",fn NSHomeDirectory)
NSLog(@"%@",fn NSTemporaryDirectory)

HandleEvents

Go

Simply
package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println(os.Getenv("SHELL"))
}
Output:
/bin/bash
Alternatively

Library function os.Environ returns all environment variables. You're on your own then to parse out the one you want. Example:

package main

import (
    "fmt"
    "os"
    "strings"
)

func main() {
    s := "SHELL"
    se := s + "="
    for _, v := range os.Environ() {
        if strings.HasPrefix(v, se) {
            fmt.Println(s, "has value", v[len(se):])
            return
        }
    }
    fmt.Println(s, "not found")
}
Output:
SHELL has value /bin/bash

Gri

Command get env fetches an environment variable into a synonym (a string)

get env \foo HOME
show "\foo"

Quotes can be used in the usual way if the environment variable name contains spaces (which is unusual, but possible).

get env \foo "X Y Z"

Groovy

System.getenv().each { property, value -> println "$property = $value"}

Haskell

import System.Environment
main = do getEnv "HOME" >>= print  -- get env var
          getEnvironment >>= print -- get the entire environment as a list of (key, value) pairs

hexiscript

println env "HOME"
println env "PATH"
println env "USER"

HicEst

CHARACTER string*255

string = "PATH="
SYSTEM(GEteNV = string)

i

software {
	print(load("$HOME"))
	print(load("$USER"))
	print(load("$PATH"))
}

Icon and Unicon

Works with: Unicon
procedure main(arglist)

if *envars = 0 then envars := ["HOME", "TRACE", "BLKSIZE","STRSIZE","COEXPSIZE","MSTKSIZE", "IPATH","LPATH","NOERRBUF"] 

every v := !sort(envars) do 
   write(v," = ",image(getenv(v))|"* not set *")
end

J

2!:5'HOME'

Java

System.getenv("HOME") // get env var
System.getenv()       // get the entire environment as a Map of keys to values

JavaScript

The JavaScript language has no facilities to access the computer: it relies on the host environment to provide it.

Works with: JScript
var shell = new ActiveXObject("WScript.Shell");
var env = shell.Environment("PROCESS");
WScript.echo('SYSTEMROOT=' + env.item('SYSTEMROOT'));

Joy

"HOME" getenv.

jq

env.HOME

If the environment variable name has spaces or special characters, the name must be given as a string, e.g. env."HOME".

jsish

The Jsi Util module provides access to set Util.setenv(name, value) and get Util.getenv(name) process environment variables. Util.getenv(), with no argument will return an object with all available name:value pairs.

/* Environment variables, in Jsi */
puts(Util.getenv("HOME"));
var environment = Util.getenv();
puts(environment.PATH);

Julia

Works with: Julia version 0.6
@show ENV["PATH"]
@show ENV["HOME"]
@show ENV["USER"]

K

_getenv "HOME"

Kotlin

// version 1.0.6

// tested on Windows 10

fun main(args: Array<String>) {
   println(System.getenv("SystemRoot"))
}
Output:
C:\WINDOWS

langur

writeln "HOME: ", _env'HOME
writeln "PATH: ", _env'PATH
writeln "USER: ", _env'USER

Lasso

#!/usr/bin/lasso9

define getenv(sysvar::string) => {
	local(regexp = regexp(
		-find = `(?m)^` + #sysvar + `=(.*?)$`,
		-input = sys_environ -> join('\n'),
		-ignorecase
	))
	return #regexp ->find ? #regexp -> matchString(1)
}

stdoutnl(getenv('HOME'))
stdoutnl(getenv('PATH'))
stdoutnl(getenv('USER'))
stdoutnl(getenv('WHAT'))
Output:
/Users/rosetta
/opt/local/bin:/opt/local/sbin:/usr/local/bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin
rosetta

Liberty BASIC

Built-in variables

print StartupDir$
print DefaultDir$

Other variables

print GetEnvironmentVariable$("USERNAME")
    print GetEnvironmentVariable$("USERPROFILE") ' equivalent to UNIX HOME variable
    print GetEnvironmentVariable$("PATH")
    end

function GetEnvironmentVariable$(lpName$)
    'get the value of an environment variable
    nSize = 1024

[Retry]
    lpBuffer$ = space$(nSize)

    calldll #kernel32, "GetEnvironmentVariableA", _
        lpName$   as ptr, _
        lpBuffer$ as ptr, _
        nSize     as ulong, _
        result    as ulong

    select case
        ' buffer too small
        case result > nSize
        nSize = result
        goto [Retry]

        ' variable found
        case result > 0
        GetEnvironmentVariable$ = left$(lpBuffer$, result)
    end select
end function

LIL

LIL does not ship with a command to retrieve process environment variables. The system command could be used, but here is an extension in C for the lil shell.

static LILCALLBACK lil_value_t fnc_env(lil_t lil, size_t argc, lil_value_t* argv)
{
    if (!argc) return NULL;
    return lil_alloc_string(getenv(lil_to_string(argv[0])));
}

Then inside the main functions for repl and nonint (Interactive, Noninteractive):

lil_register(lil, "env", fnc_env);

Now lil can get at the environment. That could fairly easily be extended further to return the entire environment array if no arguments are passed to env, this just returns an empty result for that case. Defaults values could also be supported if the named environment variable is empty. Etcetera. Setting variables would be similar, a few lines of lil C to wrap a call to libc setenv in a new command, and registering the command.

Output:
prompt$ make
cc -c -g3 -std=c99 -pedantic -Wall -Wextra -Wno-format -Wno-long-long -Wno-unused-parameter  main.c -o main.o
cc -g -L.  -o lil main.o -llil -lm

prompt$ lil
Little Interpreted Language Interactive Shell
# env TERM
xterm-256color

Lingo

Library: Shell Xtra
sx = xtra("Shell").new()
if the platform contains "win" then
  path = sx.shell_cmd("echo %PATH%").line[1]
else
  path = sx.shell_cmd("echo $PATH").line[1]
end if

Logtalk

Using the standard library:

os::environment_variable('PATH', Path).

LSL

Rez a box on the ground, and add the following as a New Script.

default {
	state_entry() {
		llOwnerSay("llGetTimestamp()="+(string)llGetTimestamp());
		llOwnerSay("llGetEnergy()="+(string)llGetEnergy());
		llOwnerSay("llGetFreeMemory()="+(string)llGetFreeMemory());
		llOwnerSay("llGetMemoryLimit()="+(string)llGetMemoryLimit());
	}
}
Output:
llGetTimestamp()=2012-07-18T01:26:12.133137Z
llGetEnergy()=1.230000
llGetFreeMemory()=16000
llGetMemoryLimit()=65536

Lua

print( os.getenv( "PATH" ) )

M2000 Interpreter

Module CheckIt {
      \\ using read only variablles
      Print "Platform: ";Platform$
      Print "Computer Os: "; Os$
      Print "Type of OS: ";OsBit;" bit"
      Print "Computer Name:";  Computer$
      Print "User Name: "; User.Name$
      \\ using WScript.Shell
      Declare objShell "WScript.Shell"
      With  objShell, "Environment" set env ("Process")
      With env, "item" as Env$()
      Print Env$("PATH")
      Print Env$("HOMEPATH")
      Declare objShell Nothing
      \\ using internal Information object
      Declare OsInfo INFORMATION
      With OsInfo, "build" as build, "NtDllVersion" as NtDllVersion$
      Method OsInfo, "GetCurrentProcessSID" as PID$
      Method OsInfo, "IsProcessElevated" as isElevated
      Print "Os build number: ";build
      Print "Nr Dll version: ";NtDllVersion$
      Print "ProcessSID: ";pid$
      Print "Is Process Eleveted: ";isElevated
      Declare OsInfo Nothing
}
Checkit

Make

Make variables are initialized from the environment, so simply

TARGET = $(HOME)/some/thing.txt
foo:
	echo $(TARGET)

The shell code in a rule can use the shell's environment in the usual way (Unix Shell), but remember $ must be doubled $$ to get a literal $ in that code.

bar:
        echo "$$HOME"

If you mistakenly write just $HOME then it means the makefile $H followed by characters OME.

H = oops ...
bar:
	echo $HOME

# prints oops ... OME

Maple

getenv("PATH");

Mathematica / Wolfram Language

Environment["PATH"]

MATLAB / Octave

    getenv('HOME')
    getenv('PATH')
    getenv('USER')

Mercury

:- module env_var.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.
:- import_module maybe, string.

main(!IO) :-
    io.get_environment_var("HOME", MaybeValue, !IO),
    (
        MaybeValue = yes(Value),
        io.write_string("HOME is " ++ Value ++ "\n", !IO)
    ;
        MaybeValue = no,
        io.write_string("environment variable HOME not set\n", !IO)
    ).

min

Works with: min version 0.19.3
$PATH

Modula-3

MODULE EnvVars EXPORTS Main;

IMPORT IO, Env;

VAR
  k, v: TEXT;

BEGIN
  IO.Put(Env.Get("HOME") & "\n");

  FOR i := 0 TO Env.Count - 1 DO
    Env.GetNth(i, k, v);
    IO.Put(k & " = " & v & "\n")
  END
END EnvVars.

MUMPS

ANSI MUMPS doesn't allow access to the operating system except possibly through the View command and $View function, both of which are implementation specific. Intersystems' Caché does allow you to create processes with the $ZF function, and if the permissions for the Caché process allow it you can perform operating system commands.

In Caché on OpenVMS in an FILES-11 filesystem ODS-5 mode these could work:

 Set X=$ZF(-1,"show logical")
 Set X=$ZF(-1,"show symbol")

NetRexx

When NetRexx runs under a JVM, system ENVIRONMENT variables are complimented by JVM system properties. This sample shows how to get both.

/* NetRexx */
options replace format comments java crossref symbols nobinary

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method sysEnvironment(vn = '') public static
  if vn.length > 0 then do
    envName = vn
    envValu = System.getenv(envName)
    if envValu = null then envValu = ''
    say envName '=' envValu
    end
  else do
    envVars = System.getenv()
    key = String
    loop key over envVars.keySet()
      envName = key
      envValu = String envVars.get(key)
      say envName '=' envValu
      end key
    end
  return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method sysProperties(vn = '') public static
  if vn.length > 0 then do
    propName = vn
    propValu = System.getProperty(propName)
    if propValu = null then propValu = ''
    say propName '=' propValu
    end
  else do
    sysProps = System.getProperties()
    key = String
    loop key over sysProps.keySet()
      propName = key
      propValu = sysProps.getProperty(key)
      say propName '=' propValu
      end key
    end
  return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) public static
  parse arg ev pv .
  if ev = '' then ev = 'CLASSPATH'
  if pv = '' then pv = 'java.class.path'
  say '-'.left(80, '-').overlay(' Environment "'ev'" ', 5)
  sysEnvironment(ev)
  say '-'.left(80, '-').overlay(' Properties "'pv'" ', 5)
  sysProperties(pv)
  say
  say '-'.left(80, '-').overlay(' Environment ', 5)
  sysEnvironment()
  say '-'.left(80, '-').overlay(' Properties ', 5)
  sysProperties()
  say
  return
Output:
---- Environment "CLASSPATH" ---------------------------------------------------
CLASSPATH = /usr/local/NetRexx/runlib/NetRexxR.jar:.
---- Properties "java.class.path" ----------------------------------------------
java.class.path = /usr/local/NetRexx/runlib/NetRexxR.jar:.

---- Environment ---------------------------------------------------------------
HOME = /Users/nrxuser
HISTCONTROL = ignoredups
USER = nrxuser
ZBASHRC = 1
COMMAND_MODE = unix2003
CLASSPATH = /usr/local/NetRexx/runlib/NetRexxR.jar:.
SHELL = /bin/bash
. . .
---- Properties ----------------------------------------------------------------
java.vm.specification.name = Java Virtual Machine Specification
sun.cpu.endian = little
sun.io.unicode.encoding = UnicodeBig
sun.os.patch.level = unknown
file.separator = /
java.vendor = Oracle Corporation
sun.java.launcher = SUN_STANDARD
java.specification.vendor = Oracle Corporation
user.home = /Users/nrxuser
java.class.path = /usr/local/NetRexx/runlib/NetRexxR.jar:.
java.vm.vendor = Oracle Corporation
java.runtime.name = Java(TM) SE Runtime Environment
. . .

NewLISP

> (env "SHELL")
"/bin/zsh"
> (env "TERM")
"xterm"

Nim

import os
echo getEnv("HOME")

NSIS

While common environment variables exist as constants within the NSIS script compilation environment (see NSIS documentation), arbitrarily-named environment variables' values may be retrieved using ExpandEnvStrings.

ExpandEnvStrings $0 "%PATH%" ; Retrieve PATH and place it in builtin register 0.
ExpandEnvStrings $1 "%USERPROFILE%" ; Retrieve the user's profile location and place it in builtin register 1.
ExpandEnvStrings $2 "%USERNAME%" ; Retrieve the user's account name and place it in builtin register 2.

Nu

$env.HOME

Objective-C

[[NSProcessInfo processInfo] environment] returns an NSDictionary of the current environment.

[[[NSProcessInfo processInfo] environment] objectForKey:@"HOME"]

OCaml

Sys.getenv "HOME"

Oforth

System getEnv("PATH") println

Oz

{System.showInfo "This is where Mozart is installed: "#{OS.getEnv 'OZHOME'}}

PARI/GP

Works with: PARI/GP version 2.6.0 and above
getenv("HOME")
Works with: PARI/GP version 2.4.3 and above
externstr("echo $HOME")
Works with: PARI/GP version 2.0.3 and above

In older versions, the command must effectively be triple-quoted:

extern("echo \"\\\"$HOME\\\"\"")

The shell sees

echo "\"$HOME\""

which causes it to return

"/home/username"

so that the result is interpreted by GP as a string.

Leaving out the quotation marks allows external commands to return expressions that are then evaluated by GP. For example,

extern("echo Pi")

causes the shell to send Pi back to GP, which interprets the result and returns

%1 = 3.141592653589793238462643383

Perl

The %ENV hash maps environment variables to their values:

print $ENV{HOME}, "\n";

The POSIXmodule also has getenv() which is the same thing as a function.

use POSIX 'getenv';
print getenv("HOME"),"\n";

Phix

without js -- none such in a browser, that I know of
?getenv("PATH")

Phixmonti

/# Rosetta Code problem: http://rosettacode.org/wiki/Environment_variables
by Galileo, 10/2022 #/

def getenv
	" > output.txt" chain cmd if "Error!" else "output.txt" "r" fopen dup fgets swap fclose endif
enddef

"path" getenv print

PHP

The $_ENV associative array maps environmental variable names to their values:

$_ENV['HOME']

PicoLisp

: (sys "TERM")
-> "xterm"

: (sys "SHELL")
-> "/bin/bash"

Pike

write("%s\n", getenv("SHELL"));
Output:
/bin/bash

PowerShell

Environment variables can be found in the Env: drive and are accessed using a special variable syntax:

$Env:Path

To get a complete listing of all environment variables one can simply query the appropriate drive for its contents:

Get-ChildItem Env:

Prolog

SWI-Prolog has the built in function getenv.

 ?- getenv('TEMP', Temp).

PureBasic

PureBasic has the built in funtion

GetEnvironmentVariable("Name")

Example

If OpenConsole()
  PrintN("Path:"+#CRLF$ + GetEnvironmentVariable("PATH"))
  PrintN(#CRLF$+#CRLF$+"NUMBER_OF_PROCESSORS= "+ GetEnvironmentVariable("NUMBER_OF_PROCESSORS"))

  PrintN(#CRLF$+#CRLF$+"Press Enter to quit.")
  Input() 
  CloseConsole()
EndIf

Python

The os.environ dictionary maps environmental variable names to their values:

import os
os.environ['HOME']

R

Sys.getenv("PATH")

Racket

#lang racket
(getenv "HOME")

Raku

(formerly Perl 6)

Works with: Rakudo version #24 "Seoul"

The %*ENV hash maps environment variables to their values:

say %*ENV<HOME>;

REBOL

print get-env "HOME"

Retro

here "HOME" getEnv
here puts

REXX

Each REXX interpreter sets its own rules by what identifies the pool in which the environmental variables are named. In addition, each operation system (OS) has their own definition as well. This makes it problematic in the accessing/acquiring of environmental variables. Most programmers know what REXX interpreter they are using, and furthermore, they also know what operating system they are writing the REXX program for, so most programmers hard-wire (explicitly code) the "access-name" of the system environmental variables into the program.

The following will work for

  • Regina
  • R4
  • ROO

for the DOS shell under Microsoft Windows (any version).
(Also successfully tested with Regina under the bash shell in UNIX.)

Works with: Regina
Works with: R4
Works with: ROO
/*REXX program shows how to get an environmental variable under Windows*/

x=value('TEMP',,'SYSTEM')

The following will work for

  • PC/REXX
  • Personal REXX
  • Regina
  • Open Object Rexx

for the DOS shell under Microsoft Windows (any version).
(Also successfully tested with Regina and ooRexx under the bash shell in UNIX.)

Works with: PC/REXX
Works with: Personal REXX
Works with: Regina
Works with: ooRexx
/*REXX program shows how to get an environmental variable under Windows*/

x=value('TEMP',,'ENVIRONMENT')

The brexx interpreter provides a getenv function for accessing environment variables:

Works with: Brexx
x=getenv("PATH") /* Get the contents of the path environment variable */

Other REXX interpreters have their own requirements to identify the SYSTEM environment.
VM/CMS has something called GLOBALV (global variables) and are of three types:

  • temporary,   lasting only for execution of the REXX program
  • temporary,   lasting only for LOGON or CMS session)
  • permanent

As such, CMS has its own command interface for these variables.

Ring

see get("path")

Ruby

The ENV hash maps environment variable names to their values:

ENV['HOME']

Run BASIC

' ------- Major environment variables -------------------------------------------
'DefaultDir$    - The folder path where program files are read/written by default
'Platform$      - The operating system on which Run BASIC is being hosted
'UserInfo$      - This is information about the user's web browser
'UrlKeys$       - Contains informational parameters from the URL submitted when the user connected
'UserAddress$   - Contains the IP address of the user
'ProjectsRoot$  - The folder path where Run BASIC keeps programming projects
'ResourcesRoot$ - The folder path where Run BASIC keeps web-servable files
'Err$           - A description of the last runtime error
'Err            - A numeric code for the last runtime error (errors that have no code use zero)
'EventKey$      - The id of the object that generated the last user event
'RowIndex       - The numeric index of the table or database accessor link that generated the last user event


print "User Info is   : ";UserInfo$
print "Platform is    : ";Platform$
print "Url Keys is    : ";UrlKeys$
print "User Address is: ";UserAddress$
print "Event Key is   : ";EventKey$
print "Default Dir is : ";DefaultDir$
{{out}}
User Info is   : Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11
Platform is    : win32
Url Keys is    : none
User Address is: 127.0.0.1
Event Key is   : none
Default Dir is : c:\rbp101

Rust

use std::env;

fn main() {
    println!("{:?}", env::var("HOME"));
    println!();
    for (k, v) in env::vars().filter(|(k, _)| k.starts_with('P')) {
        println!("{}: {}", k, v);
    }
}
Output:
Ok("/root")

PATH: /root/.cargo/bin:/root/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
PLAYGROUND_EDITION: 2018
PLAYGROUND_TIMEOUT: 10
PWD: /playground

Note that var_os and vars_os are also available, which produce OsString instead of String, offering compatibility with non-utf8 systems.

Scala

sys.env.get("HOME")

Seed7

Seed7 provides the function getenv, to get the value of an environment variable. Environment variables are highly operating system dependent. Some variables such as HOME are not always defined and others like PATH use an operating system dependent format (different delimiters). Seed7 provides the functions homeDir and getSearchPath to get the home directory and the search path in an operating system independent manner.

$ include "seed7_05.s7i";
 
const proc: main is func
  begin
    writeln(getenv("HOME"));
  end func;

Sidef

The ENV hash maps environment variables to their values:

say ENV{'HOME'};

Slate

Environment variables at: 'PATH'.
"==> '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'"

Slope

(env "HOME")

Smalltalk

Use the OSProcess library to gain access to environment variables:

OSProcess thisOSProcess environment at: #HOME.
OSProcess thisOSProcess environment at: #PATH.
OSProcess thisOSProcess environment at: #USER.

SNOBOL4

Works with: Macro Spitbol
Works with: CSnobol

The host(4) function returns a known environment variable.

         output = host(4,'PATH')
end

Standard ML

OS.Process.getEnv "HOME"

returns an option type which is either SOME value or NONE if variable doesn't exist

Stata

Use the env extended macro function.

display "`:env PATH'"
display "`:env USERNAME'"
display "`:env USERPROFILE'"

Swift

print("USER: \(ProcessInfo.processInfo.environment["USER"] ?? "Not set")")
print("PATH: \(ProcessInfo.processInfo.environment["PATH"] ?? "Not set")")

True BASIC

ASK #1: ACCESS type$
ASK BACK red
ASK COLOR red
ASK COLOR MIX (2) red, green, blue
ASK CURSOR vble1, vble2
ASK #2: DATUM type$
ASK DIRECTORY dir$
ASK #3: ERASABLE type$
ASK #4: FILESIZE vble09
ASK #5: FILETYPE vble10
ASK FREE MEMORY vble11
ASK #61: MARGIN vble12
ASK MAX COLOR vble13
ASK MAX CURSOR vble1, vble2
ASK MODE vble15$
ASK NAME vble16$
ASK #7: ORGANIZATION vble17$
ASK PIXELS vble1, vble2
ASK #8: POINTER vble19$
ASK #9: RECORD vble20
ASK #1: RECSIZE vble21
ASK #2: RECTYPE vble22$
ASK SCREEN vble1, vble2, vble3, vble4
ASK #3: SETTER vble24$
ASK TEXT JUSTIFY vble1$, vble2$
ASK WINDOW vble1, vble2, vble3, vble4
ASK #4: ZONEWIDTH vble27

Tcl

The env global array maps environmental variable names to their values:

$env(HOME)

TXR

TXR can treat the environment vector as text stream:

@(next :env)
@(collect)
@VAR=@VAL
@(end)

A recently added gather directive is useful for extracting multiple items of data from an unordered stream of this kind (not only the environment vector):

@(next :env)
@(gather)
HOME=@home
USER=@user
PATH=@path
@(end)

What if some of the variables might not exist? Gather has some discipline for that. The following means that three variables are required (the gather construct fails if they are not found), but shell is optional with a default value of /bin/sh if it is not extracted from the data:

@(next :env)
@(gather :vars (home user path (shell "/bin/sh")))
HOME=@home
USER=@user
PATH=@path
SHELL=@shell
@(end)

From TXR Lisp, the environment is available via the (env) function, which returns a raw list of "name=value strings. The (env-hash) function returns a hash from environment keys to their values.

$ ./txr -p "(mapcar (env-hash) '(\"HOME\" \"USER\" \"PATH\"))"
("/home/kaz" "kaz" "/home/kaz/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/kaz/bin"

Here, the hash is being used as a function to filter several environment keys to their values via mapcar.


Platform note: On POSIX, environment variables, which are extracted using extern char **environ are assumed to contain UTF-8. On Windows, the GetEnvironmentStringsW function is used to obtain the environment vector as wide character data.

UNIX Shell

In the Unix Shell Language, environment variables are available as ordinary variables:

echo "$HOME"

An ordinary variable can be marked as an environment variable with the export command:

export VAR

Now child processes launched by the shell will have an environment variable called VAR.

The Unix command "env" will print out all of the environment variables as key=value pairs on standard output.

Ursa

import "system"
out (system.getenv "HOME") endl console

Ursala

The argument to the main program is a record initialized by the run-time system in which one of the fields (environs) contains the environment as a list of key:value pairs.

#import std

#executable ('parameterized','')

showenv = <.file$[contents: --<''>]>+ %smP+ ~&n-={'TERM','SHELL','X11BROWSER'}*~+ ~environs

The rest of this application searches for the three variables named and displays them on standard output.

Here is a bash session:
$ showenv
<
   'TERM': 'Eterm',
   'SHELL': '/bin/bash',
   'X11BROWSER': '/usr/bin/firefox'>

V (Vlang)

// Environment variables in V
// v run environment_variables.v
module main

import os

pub fn main() {
    print('In the $os.environ().len environment variables, ')
    println('\$HOME is set to ${os.getenv('HOME')}')
}
Output:
prompt$ v run environment-variables.v
In the 64 environment variables, $HOME is set to /home/btiffin

Vedit macro language

Get_Environment(10,"PATH")
Message(@10)

Or with short keywords:

GE(10,"PATH") M(@10)

Visual Basic

Works with: Visual Basic version VB6 Standard
Debug.Print Environ$("PATH")

Wren

Wren CLI doesn't currently expose a way to obtain the value of an environment variable.

However, if Wren is embedded in (say) a suitable Go program, then we can ask the latter to obtain it for us.

/* Environment_variables.wren */
class Environ {
    foreign static variable(name)
}

System.print(Environ.variable("SHELL"))

which we embed in the following Go program and run it.

Library: WrenGo
/* Environment_variables.go */
package main

import (
    wren "github.com/crazyinfin8/WrenGo"
    "os"
)

type any = interface{}

func getEnvironVariable(vm *wren.VM, parameters []any) (any, error) {
    name := parameters[1].(string)
    return os.Getenv(name), nil
}

func main() {
    vm := wren.NewVM()
    fileName := "Environment_variables.wren"
    methodMap := wren.MethodMap{"static variable(_)": getEnvironVariable}
    classMap := wren.ClassMap{"Environ": wren.NewClass(nil, nil, methodMap)}
    module := wren.NewModule(classMap)
    vm.SetModule(fileName, module)
    vm.InterpretFile(fileName)
    vm.Free()
}
Output:
/bin/bash

XPL0

This task was particularly worthwhile because it revealed a discrepancy in the way 32-bit XPL0 accessed the environment block. A small mod to Tran's PMODE.ASM DPMI was required to make the 32-bit protected-mode version work the same as the 16-bit real-mode versions.

include c:\cxpl\codes;          \intrinsic 'code' declarations
string 0;                       \use zero-terminated strings
int  CpuReg, PspSeg, EnvSeg, I, J, C;
char EnvVar;
[CpuReg:= GetReg;               \access CPU registers
PspSeg:= CpuReg(9);             \get segment address of our PSP
EnvSeg:= Peek(PspSeg,$2C) + Peek(PspSeg,$2D)<<8;
EnvVar:= "PATH";                \environment variable
I:= 0;
loop    [J:= 0;
        loop    [C:= Peek(EnvSeg,I);  I:= I+1;
                if C = 0 then quit;
                if C = EnvVar(J) then
                        [J:= J+1;
                        if J = 4 then
                                [Text(0, EnvVar);               \show env. var.
                                loop    [C:= Peek(EnvSeg,I);    \ and rest of
                                        I:= I+1;                \ its string
                                        if C = 0 then exit;
                                        ChOut(0, C);
                                        ];
                                ];
                        ]
                else J:= 5;     \line must start with environment variable
                ];
        if Peek(EnvSeg,I) = 0 then quit;        \double 0 = env. var. not found
        ];
]
Output:
PATH=\masm6;C:\;C:\CXPL;C:\UTIL;C:\DOS;C:\BORLANDC\BIN

Yabasic

peek$("env","NAME") Return the environment variable specified by NAME (which may be any string expression).

Which kind of environment variables are available on your system depends, as well as their meaning, on your system; however typing env on the command line will produce a list (for Windows and Unix alike).

Note, that peek$("env",...) can be written as peek$("environment",...) too.

zkl

System.getenv("HOME")
/home/craigd
System.getenv() //--> Dictionary of all env vars