Environment variables
You are encouraged to solve this task according to the task description, using any language you may know.
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.
Ada
Print a single environment variable. <lang ada>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;</lang> Print all environment variable names and values. <lang ada>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;</lang>
ALGOL 68
<lang algol68>print((getenv("HOME"), new line))</lang>
AutoHotkey
<lang autohotkey>EnvGet, OutputVar, Path MsgBox, %OutputVar%</lang>
AWK
The ENVIRON array contains the values of the current environment: <lang awk>$ awk 'BEGIN{print "HOME:"ENVIRON["HOME"],"USER:"ENVIRON["USER"]}' HOME:/home/suchrich USER:SuchRich</lang> 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}' HOME:/home/suchrich USER:SuchRich</lang>
BASIC
<lang qbasic>x$ = ENVIRON$("path") PRINT x$ </lang>
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:
<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 30 POKE 23609,50: REM set keyboard pip to 50 </lang>
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:
<lang dos>echo %Foo%</lang>
For interactive use one can use set
to view all environment variables or all variables starting with a certain string:
<lang dos>set
set Foo</lang>
BBC BASIC
<lang bbcbasic> 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%</lang>
C
<lang c>#include <stdlib.h>
- include <stdio.h>
int main() {
puts(getenv("HOME")); return 0;
}</lang>
C++
<lang cpp>#include <cstdlib>
- include <cstdio>
int main() {
puts(getenv("HOME")); return 0;
}</lang>
C#
<lang csharp>using System;
namespace RosettaCode {
class Program { static void Main() { string temp = Environment.GetEnvironmentVariable("TEMP"); Console.WriteLine("TEMP is " + temp); } }
}</lang>
Clojure
<lang lisp> (System/getenv "HOME") </lang>
D
<lang d>import std.stdio, std.process;
void main() {
writeln(getenv("HOME"));
}</lang>
<lang d>import tango.sys.Environment;
void main() {
auto home = Environment("HOME");
}</lang>
Common Lisp
Access to environment variables isn't a part of the Common Lisp standard, but most implementations provide some way to do it.
<lang lisp>(lispworks:environment-variable "USER")</lang>
<lang lisp>(sb-ext:posix-getenv "USER")</lang>
<lang lisp>(ccl:getenv "USER")</lang>
<lang lisp>(getenv "HOME")</lang>
Ways to do this in some other implementations are listed in the Common Lisp Cookbook.
Delphi
<lang Delphi>program EnvironmentVariable;
{$APPTYPE CONSOLE}
uses SysUtils;
begin
WriteLn('Temp = ' + GetEnvironmentVariable('TEMP'));
end.</lang>
E
<lang e><unsafe:java.lang.System>.getenv("HOME")</lang>
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.
<lang eiffel >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</lang>
Emacs Lisp
<lang lisp>(getenv "HOME")</lang>
Euphoria
<lang euphoria>puts(1,getenv("PATH"))</lang>
Factor
<lang factor>"HOME" os-env print</lang>
Forth
<lang forth>s" HOME" getenv type</lang>
Fortran
<lang 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 </lang>
Go
Simply: <lang go> package main
import (
"fmt" "os"
)
func main() {
fmt.Println(os.Getenv("SHELL"))
}</lang> 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: <lang go>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")
}</lang> Output:
SHELL has value /bin/bash
Haskell
<lang 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</lang>
HicEst
<lang HicEst>CHARACTER string*255
string = "PATH=" SYSTEM(GEteNV = string)</lang>
Icon and Unicon
<lang Icon>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</lang>
J
<lang j>2!:5'HOME'</lang>
Java
<lang java>System.getenv("HOME") // get env var System.getenv() // get the entire environment as a Map of keys to values</lang>
JavaScript
The JavaScript language has no facilities to access the computer: it relies on the host environment to provide it.
<lang javascript>var shell = new ActiveXObject("WScript.Shell"); var env = shell.Environment("PROCESS"); WScript.echo('SYSTEMROOT=' + env.item('SYSTEMROOT'));</lang>
Joy
<lang joy>"HOME" getenv.</lang>
Liberty BASIC
Built-in variables
<lang lb>print StartupDir$ print DefaultDir$</lang>
Other variables
<lang lb>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</lang>
Lua
<lang lua>print( os.getenv( "PATH" ) )</lang>
Mathematica
<lang Mathematica>Environment["PATH"]</lang>
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:
<lang MUMPS> Set X=$ZF(-1,"show logical")
Set X=$ZF(-1,"show symbol")</lang>
NewLISP
<lang NewLISP>> (env "SHELL") "/bin/zsh" > (env "TERM") "xterm" </lang>
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. <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 $2 "%USERNAME%" ; Retrieve the user's account name and place it in builtin register 2.</lang>
Objective-C
[[NSProcessInfo processInfo] environment]
returns an NSDictionary of the current environment.
<lang objc>[[[NSProcessInfo processInfo] environment] objectForKey:@"HOME"]</lang>
OCaml
<lang ocaml>Sys.getenv "HOME"</lang>
Oz
<lang oz>{System.showInfo "This is where Mozart is installed: "#{OS.getEnv 'OZHOME'}}</lang>
PARI/GP
<lang parigp>system("echo $HOME")</lang>
Pascal
See Delphi
Perl
The %ENV
hash maps environment variables to their values:
<lang perl>print $ENV{HOME}, "\n";</lang>
Perl 6
The %*ENV
hash maps environment variables to their values:
<lang perl6>say %*ENV<HOME>;</lang>
PHP
The $_ENV associative array maps environmental variable names to their values: <lang php>$_ENV['HOME']</lang>
PicoLisp
<lang PicoLisp>: (sys "TERM") -> "xterm"
- (sys "SHELL")
-> "/bin/bash"</lang>
PowerShell
Environment variables can be found in the Env: drive and are accessed using a special variable syntax: <lang powershell>$Env:Path</lang> 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>
PureBasic
PureBasic has the built in funtion <lang PureBasic>GetEnvironmentVariable("Name")</lang>
Example
<lang PureBasic>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</lang>
Python
The os.environ dictionary maps environmental variable names to their values: <lang python>import os os.environ['HOME']</lang>
R
<lang R>Sys.getenv("PATH")</lang>
REBOL
<lang REBOL>print get-env "HOME"</lang>
Retro
<lang Retro>here "HOME" getEnv here puts</lang>
REXX
Each REXX interpreter sets its own rules by what identify the environmental variables are named.
In addition, each operation system (OS) hase their own definition as well.
This makes it problamatic in the acessing/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 and R4 for the DOS shell under Windows (any version).
<lang rexx>
/*REXX program shows how to get an environmental variable under Windows*/
x=value('TEMP',,'SYSTEM') </lang> The following will work for PC/REXX and Regina for the DOS shell under Windows (any version). <lang rexx> /*REXX program shows how to get an environmental variable under Windows*/
x=value('TEMP',,'ENVIRONMENT')
</lang>
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.
Ruby
The ENV hash maps environmental variable names to their values: <lang ruby>ENV['HOME']</lang>
Seed7
<lang seed7>$ include "seed7_05.s7i";
const proc: main is func
begin writeln(getenv("HOME")); end func;</lang>
Slate
<lang slate>Environment variables at: 'PATH'. "==> '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'"</lang>
Standard ML
<lang sml>OS.Process.getEnv "HOME"</lang> returns an option type which is either SOME value or NONE if variable doesn't exist
SNOBOL4
The host(4) function returns a known environment variable. <lang SNOBOL4> output = host(4,'PATH') end</lang>
Tcl
The env
global array maps environmental variable names to their values:
<lang tcl>$env(HOME)</lang>
TXR
TXR can treat the environment vector as text stream:
<lang txr>@(next :env) @(collect) @VAR=@VAL @(end)</lang>
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):
<lang txr>@(next :env) @(gather) HOME=@home USER=@user PATH=@path @(end)</lang>
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:
<lang txr>@(next :env) @(gather :vars (home user path (shell "/bin/sh"))) HOME=@home USER=@user PATH=@path SHELL=@shell @(end)</lang>
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:
<lang bash>echo $HOME</lang>
An ordinary variable can be marked as an environment variable with the export
command:
<lang bash>export VAR</lang>
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.
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. <lang Ursala>#import std
- executable ('parameterized',)
showenv = <.file$[contents: --<>]>+ %smP+ ~&n-={'TERM','SHELL','X11BROWSER'}*~+ ~environs</lang> 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'>
Vedit macro language
<lang vedit>Get_Environment(10,"PATH") Message(@10)</lang>
Or with short keywords: <lang vedit>GE(10,"PATH") M(@10)</lang>
- Programming Tasks
- Programming environment operations
- Ada
- ALGOL 68
- AutoHotkey
- AWK
- BASIC
- ZX Spectrum Basic
- Batch File
- BBC BASIC
- C
- C++
- C sharp
- Clojure
- D
- Phobos
- Tango
- Common Lisp
- Delphi
- E
- Eiffel
- Emacs Lisp
- Euphoria
- Factor
- Forth
- Fortran
- Go
- Haskell
- HicEst
- Icon
- Unicon
- J
- Java
- JavaScript
- Joy
- Liberty BASIC
- Lua
- Mathematica
- MUMPS
- NewLISP
- NSIS
- Objective-C
- OCaml
- Oz
- PARI/GP
- PARI/GP examples needing attention
- Examples needing attention
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- PowerShell
- PureBasic
- Python
- R
- REBOL
- Retro
- REXX
- Ruby
- Seed7
- Slate
- Standard ML
- SNOBOL4
- Tcl
- TXR
- UNIX Shell
- Ursala
- Vedit macro language
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit
- M4/Omit
- Unlambda/Omit
- Environment variables
- Initialization