Environment variables: Difference between revisions
Content deleted Content added
Added Erlang |
Add SmallBASIC |
||
(93 intermediate revisions by 56 users not shown) | |||
Line 1:
{{task|Programming environment operations}}
[[Category:Environment variables]]
[[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; some of the common ones available on Unix include:
:::* PATH
:::* HOME
:::* USER
<br><br>
=={{header|11l}}==
<syntaxhighlight lang="11l">print(os:getenv(‘HOME’))</syntaxhighlight>
=={{header|Ada}}==
Print a single environment variable.
<
with Ada.Text_Io; use Ada.Text_Io;
Line 10 ⟶ 27:
begin
Put_Line("Path : " & Value("PATH"));
end Print_Path;</
Print all environment variable names and values.
<
with Ada.Text_Io; use Ada.Text_Io;
Line 22 ⟶ 39:
begin
Iterate(Print_Vars'access);
end Env_Vars;</
Line 29 ⟶ 46:
Uses [http://forge.ada-ru.org/matreshka Matreshka].
<
with League.Application;
Line 43 ⟶ 60:
Ada.Wide_Wide_Text_IO.Put_Line
(League.Application.Environment.Value (+"HOME").To_Wide_Wide_String);
end Main;</
=={{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}}
<
=={{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}}==
<
MsgBox, %OutputVar%</
=={{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}}==
The ENVIRON array contains the values of the current environment:
<
{{out}}
<pre>
HOME:/home/suchrich USER:SuchRich</pre>
Environment variables can also be assigned to awk variables before execution, with (-v) options:
<
{{out}}
<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}}==
<
PRINT x$</
==={{header|BaCon}}===
''Case matters and needs to match''
<syntaxhighlight lang="freebasic">PRINT GETENVIRON$("PATH")</syntaxhighlight>
==={{header|IS-BASIC}}===
<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
<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>
===
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:
<
20 PRINT "The ramtop address is "; PEEK (23730) + 256 * PEEK (23731): REM ramtop
30 POKE 23609,50: REM set keyboard pip to 50</
=={{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:
<syntaxhighlight lang
For interactive use one can use <code>set</code> to view all environment variables or all variables starting with a certain string:
<
set Foo</
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
PRINT FNenvironment("USERNAME")
END
Line 89 ⟶ 223:
DIM buffer% LOCAL size%
SYS "GetEnvironmentVariable", envar$, buffer%, size%+1
= $$buffer%</
=={{header|C}}==
<
#include <stdio.h>
int main() {
puts(getenv("HOME"));
puts(getenv("PATH"));
puts(getenv("USER"));
return 0;
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
<
namespace RosettaCode {
Line 120 ⟶ 247:
}
}
}</
=={{header|C++}}==
<syntaxhighlight lang="cpp">#include <cstdlib>
#include <cstdio>
int main()
{
puts(getenv("HOME"));
return 0;
}</syntaxhighlight>
=={{header|Clojure}}==
<
=={{header|COBOL}}==
<
PROGRAM-ID. Environment-Vars.
Line 143 ⟶ 280:
GOBACK
.</
=={{header|CoffeeScript}}==
{{works with|node.js}}
<
console.log var_name, process.env[var_name]</
=={{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.
{{works with|LispWorks}}
<syntaxhighlight lang="lisp">(lispworks:environment-variable "USER")</syntaxhighlight>
{{works with|SBCL}}
<syntaxhighlight lang="lisp">(sb-ext:posix-getenv "USER")</syntaxhighlight>
{{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}}==
{{libheader|phobos}}
<
void main() {
auto home = getenv("HOME");
}</
{{libheader|tango}}
<
void main() {
auto home = Environment("HOME");
}</
=={{header|Delphi}}/{{header|Pascal}}==
<
{$APPTYPE CONSOLE}
Line 185 ⟶ 322:
begin
WriteLn('Temp = ' + GetEnvironmentVariable('TEMP'));
end.</
=={{header|E}}==
{{works with|E-on-Java}}
<
=={{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.
<
APPLICATION
inherit
Line 205 ⟶ 342:
print (get ("USERNAME"))
end
end</
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">System.get_env("PATH")</syntaxhighlight>
=={{header|Emacs Lisp}}==
<
=={{header|EMal}}==
<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|F_Sharp|F#}}==
<
[<EntryPoint>]
let main args =
printfn "%A" (Environment.GetEnvironmentVariable("PATH"))
0</
=={{header|Factor}}==
<
=={{header|Forth}}==
{{works with|GNU Forth}}
<
=={{header|Fortran}}==
{{works with|any Fortran compiler}}
<
implicit none
character(len=32) :: home_val ! The string value of the variable HOME
Line 249 ⟶ 405:
write(*,'(a)') 'No HOME to go to!'
end if
end program show_home</
=={{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}}==
;Simply:
<
import (
Line 262 ⟶ 456:
func main() {
fmt.Println(os.Getenv("SHELL"))
}</
{{out}}
<pre>
/bin/bash
</pre>
;Alternatively:
Library function os.Environ returns all environment variables.
You're on your own then to parse out the one you want.
Example:
<syntaxhighlight lang="go">package main
import (
Line 287 ⟶ 483:
}
fmt.Println(s, "not found")
}</
{{out}}
<pre>
SHELL has value /bin/bash
</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}}==
<
=={{header|Haskell}}==
<
main = do getEnv "HOME" >>= print -- get env var
getEnvironment >>= print -- get the entire environment as a list of (key, value) pairs</
=={{header|hexiscript}}==
<syntaxhighlight lang="hexiscript">println env "HOME"
println env "PATH"
println env "USER"</syntaxhighlight>
=={{header|HicEst}}==
<
string = "PATH="
SYSTEM(GEteNV = string)</
=={{header|i}}==
<syntaxhighlight lang="i">software {
print(load("$HOME"))
print(load("$USER"))
print(load("$PATH"))
}</syntaxhighlight>
=={{header|Icon}} and {{header|Unicon}}==
{{works with|Unicon}}
<
if *envars = 0 then envars := ["HOME", "TRACE", "BLKSIZE","STRSIZE","COEXPSIZE","MSTKSIZE", "IPATH","LPATH","NOERRBUF"]
Line 315 ⟶ 531:
every v := !sort(envars) do
write(v," = ",image(getenv(v))|"* not set *")
end</
=={{header|J}}==
<syntaxhighlight lang
=={{header|Java}}==
<
System.getenv() // get the entire environment as a Map of keys to values</
=={{header|JavaScript}}==
The JavaScript language has no facilities to access the computer: it relies on the host environment to provide it.
{{works with|JScript}}
<
var env = shell.Environment("PROCESS");
WScript.echo('SYSTEMROOT=' + env.item('SYSTEMROOT'));</
=={{header|Joy}}==
<
=={{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}}==
<
=={{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}}==
=== Built-in variables ===
<
print DefaultDir$</
=== Other variables ===
<
print GetEnvironmentVariable$("USERPROFILE") ' equivalent to UNIX HOME variable
print GetEnvironmentVariable$("PATH")
Line 370 ⟶ 646:
GetEnvironmentVariable$ = left$(lpBuffer$, result)
end select
end function</
=={{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.
<
state_entry() {
llOwnerSay("llGetTimestamp()="+(string)llGetTimestamp());
Line 381 ⟶ 695:
llOwnerSay("llGetMemoryLimit()="+(string)llGetMemoryLimit());
}
}</
{{out}}
<pre>llGetTimestamp()=2012-07-18T01:26:12.133137Z
llGetEnergy()=1.230000
Line 389 ⟶ 703:
=={{header|Lua}}==
<
=={{header|
<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}}==
<
getenv('PATH')
getenv('USER')</
=={{header|Mercury}}==
<
:- interface.
Line 417 ⟶ 782:
MaybeValue = no,
io.write_string("environment variable HOME not set\n", !IO)
).</
=={{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
Env.GetNth(i, k, v);
IO.Put(k & " = " & v & "\n")
END
END EnvVars.</syntaxhighlight>
=={{header|MUMPS}}==
Line 423 ⟶ 809:
In Caché on OpenVMS in an FILES-11 filesystem ODS-5 mode these could work:
<
Set X=$ZF(-1,"show symbol")</
=={{header|NetRexx}}==
When NetRexx runs under a JVM, system ENVIRONMENT variables are complimented by JVM system properties. This sample shows how to get both.
<
options replace format comments java crossref symbols nobinary
Line 488 ⟶ 874:
say
return
</syntaxhighlight>
{{out}}
<pre>
---- Environment "CLASSPATH" ---------------------------------------------------
Line 522 ⟶ 908:
=={{header|NewLISP}}==
<
"/bin/zsh"
> (env "TERM")
"xterm"</
=={{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'''].
<
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.</
=={{header|Nu}}==
<syntaxhighlight lang="nu">
$env.HOME
</syntaxhighlight>
=={{header|Objective-C}}==
<code>[[NSProcessInfo processInfo] environment]</code> returns an <tt>NSDictionary</tt> of the current environment.
<
=={{header|OCaml}}==
<
=={{header|Oforth}}==
<syntaxhighlight lang="oforth">System getEnv("PATH") println</syntaxhighlight>
=={{header|Oz}}==
<
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.6.0 and above}}
<
{{works with|PARI/GP|2.4.3 and above}}
<
{{works with|PARI/GP|2.0.3 and above}}
In older versions, the command must effectively be triple-quoted:
<
The shell sees
<
which causes it to return
<pre>"/home/username"</pre>
Line 558 ⟶ 957:
Leaving out the quotation marks allows external commands to return expressions that are then evaluated by GP. For example,
<
causes the shell to send Pi back to GP, which interprets the result and returns
<pre>%1 = 3.141592653589793238462643383</pre>
Line 564 ⟶ 963:
=={{header|Perl}}==
The <code>%ENV</code> hash maps environment variables to their values:
<
The <code>POSIX</code>module also has <code>getenv()</code> which is the same thing as a function.
<syntaxhighlight lang="perl">use POSIX 'getenv';
print getenv("HOME"),"\n";</syntaxhighlight>
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
<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}}==
The <tt>$_ENV</tt> associative array maps environmental variable names to their values:
<syntaxhighlight lang
=={{header|PicoLisp}}==
<
-> "xterm"
: (sys "SHELL")
-> "/bin/bash"</
=={{header|Pike}}==
<syntaxhighlight lang="pike">write("%s\n", getenv("SHELL"));</syntaxhighlight>
{{Out}}
<pre>
/bin/bash
</pre>
=={{header|PowerShell}}==
Environment variables can be found in the Env: drive and are accessed using a special variable syntax:
<syntaxhighlight lang
To get a complete listing of all environment variables one can simply query the appropriate drive for its contents:
<syntaxhighlight lang
=={{header|Prolog}}==
Line 592 ⟶ 1,013:
<pre> ?- getenv('TEMP', Temp).
</pre>
=={{header|PureBasic}}==
PureBasic has the built in funtion
<
'''Example'''
<
PrintN("Path:"+#CRLF$ + GetEnvironmentVariable("PATH"))
PrintN(#CRLF$+#CRLF$+"NUMBER_OF_PROCESSORS= "+ GetEnvironmentVariable("NUMBER_OF_PROCESSORS"))
Line 603 ⟶ 1,025:
Input()
CloseConsole()
EndIf</
=={{header|Python}}==
The <tt>os.environ</tt> dictionary maps environmental variable names to their values:
<
os.environ['HOME']</
=={{header|R}}==
<
=={{header|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|Retro}}==
<
here puts</
=={{header|REXX}}==
Line 638 ⟶ 1,066:
{{works with|R4}}
{{works with|ROO}}
<
x=value('TEMP',,'SYSTEM')</
The following will work for
::* '''PC/REXX'''
Line 652 ⟶ 1,080:
{{works with|Regina}}
{{works with|ooRexx}}
<
x=value('TEMP',,'ENVIRONMENT')</
The brexx interpreter provides a getenv function for accessing environment variables:
{{works with|Brexx}}
<
Other REXX interpreters have their own requirements to identify the SYSTEM environment.
Line 666 ⟶ 1,094:
::* permanent
As such, CMS has its own command interface for these variables.
=={{header|Ring}}==
<syntaxhighlight lang="ring">
see get("path")
</syntaxhighlight>
=={{header|Ruby}}==
The <tt>ENV</tt> hash maps environment variable names to their values:
<syntaxhighlight lang
=={{header|Run BASIC}}==
<
'DefaultDir$ - The folder path where program files are read/written by default
'Platform$ - The operating system on which Run BASIC is being hosted
Line 691 ⟶ 1,124:
print "User Address is: ";UserAddress$
print "Event Key is : ";EventKey$
print "Default Dir is : ";DefaultDir$</
<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
Line 701 ⟶ 1,134:
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}}==
Line 707 ⟶ 1,163:
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.
<
const proc: main is func
begin
writeln(getenv("HOME"));
end func;</
=={{header|Sidef}}==
The ''ENV'' hash maps environment variables to their values:
<syntaxhighlight lang="ruby">say ENV{'HOME'};</syntaxhighlight>
=={{header|Slate}}==
<
"==> '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'"</
=={{header|
<syntaxhighlight lang="slope">(env "HOME")</syntaxhighlight>
=={{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}}==
Line 729 ⟶ 1,197:
{{works with|CSnobol}}
The host(4) function returns a known environment variable.
<
end</
=={{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}}==
The <code>env</code> global array maps environmental variable names to their values:
<syntaxhighlight lang
=={{header|TXR}}==
TXR can treat the environment vector as text stream:
<
@(collect)
@VAR=@VAL
@(end)</
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):
<
@(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 <code>shell</code> is optional with a default value of <code>/bin/sh</code> if it is not extracted from the data:
<
@(gather :vars (home user path (shell "/bin/sh")))
HOME=@home
Line 756 ⟶ 1,269:
PATH=@path
SHELL=@shell
@(end)</
<syntaxhighlight lang="bash">$ ./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"</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}}==
In the Unix Shell Language, environment variables are available as ordinary variables:
<
An ordinary variable can be marked as an environment variable with the <code>export</code> command:
<syntaxhighlight lang
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.
=={{header|Ursa}}==
<syntaxhighlight lang="ursa">import "system"
out (system.getenv "HOME") endl console</syntaxhighlight>
=={{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.
<
#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.
{{out|Here is a bash session}}
<pre>
$ showenv
Line 783 ⟶ 1,311:
'SHELL': '/bin/bash',
'X11BROWSER': '/usr/bin/firefox'></pre>
=={{header|V (Vlang)}}==
<syntaxhighlight lang="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')}')
}</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}}==
<
Message(@10)</
Or with short keywords:
<
=={{header|Visual Basic}}==
{{works with|Visual Basic|VB6 Standard}}
<syntaxhighlight lang="vb">Debug.Print Environ$("PATH")</syntaxhighlight>
=={{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}}==
Line 796 ⟶ 1,387:
version work the same as the 16-bit real-mode versions.
<
string 0; \use zero-terminated strings
int CpuReg, PspSeg, EnvSeg, I, J, C;
Line 823 ⟶ 1,414:
if Peek(EnvSeg,I) = 0 then quit; \double 0 = env. var. not found
];
]</
{{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}}==
<syntaxhighlight lang="zkl">System.getenv("HOME")
/home/craigd
System.getenv() //--> Dictionary of all env vars</syntaxhighlight>
|