Environment variables
From Rosetta Code
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.
[edit] 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;
[edit] 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))
[edit] AutoHotkey
EnvGet, OutputVar, Path
MsgBox, %OutputVar%
[edit] AWK
The ENVIRON array contains the values of the current environment:
$ awk 'BEGIN{print "HOME:"ENVIRON["HOME"],"USER:"ENVIRON["USER"]}'
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}'
HOME:/home/suchrich USER:SuchRich
[edit] BASIC
x$ = ENVIRON$("path")
PRINT x$
[edit] 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
[edit] C
#include <stdlib.h>
#include <stdio.h>
int main() {
puts(getenv("HOME"));
return 0;
}
[edit] C++
#include <cstdlib>
#include <cstdio>
int main()
{
puts(getenv("HOME"));
return 0;
}
[edit] C#
using System;
namespace RosettaCode {
class Program {
static void Main() {
string temp = Environment.GetEnvironmentVariable("TEMP");
Console.WriteLine("TEMP is " + temp);
}
}
}
[edit] Clojure
(System/getenv "HOME")
[edit] D
Library: tango
import tango.sys.Environment;
void main()
{
auto home = Environment("HOME");
}
[edit] 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")
Ways to do this in some other implementations are listed in the Common Lisp Cookbook.
[edit] E
Works with: E-on-Java
<unsafe:java.lang.System>.getenv("HOME")
[edit] 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
[edit] Emacs Lisp
(getenv "HOME")
[edit] Factor
"HOME" os-env print
[edit] Forth
Works with: GNU Forth
s" HOME" getenv type
[edit] Fortran
Works with: any Fortran compiler
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
[edit] 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
[edit] HicEst
CHARACTER string*255
string = "PATH="
SYSTEM(GEteNV = string)
[edit] Icon and Unicon
[edit] 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
[edit] Unicon
This Icon solution works in Unicon.
[edit] J
2!:5'HOME'
[edit] Java
System.getenv("HOME") // get env var
System.getenv() // get the entire environment as a Map of keys to values
[edit] 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'));
[edit] Joy
"HOME" getenv.
[edit] Liberty BASIC
[edit] Built-in variables
print StartupDir$
print DefaultDir$
[edit] 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
[edit] Mathematica
Environment["PATH"]
[edit] 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")
[edit] 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.
[edit] Objective-C
[[NSProcessInfo processInfo] environment] returns an NSDictionary of the current environment.
[[[NSProcessInfo processInfo] environment] objectForKey:@"HOME"]
[edit] OCaml
Sys.getenv "HOME"
[edit] Oz
{System.showInfo "This is where Mozart is installed: "#{OS.getEnv 'OZHOME'}}
[edit] Perl
The %ENV hash maps environment variables to their values:
print $ENV{HOME}, "\n";
[edit] Perl 6
Works with: Rakudo version #24 "Seoul"
The %*ENV hash maps environment variables to their values:
say %*ENV<HOME>;
[edit] PHP
The $_ENV associative array maps environmental variable names to their values:
$_ENV['HOME']
[edit] PicoLisp
: (sys "TERM")
-> "xterm"
: (sys "SHELL")
-> "/bin/bash"
[edit] 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:
[edit] 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
[edit] Python
The os.environ dictionary maps environmental variable names to their values:
import os
os.environ['HOME']
[edit] R
Sys.getenv("PATH")
[edit] REBOL
print get-env "HOME"
[edit] Ruby
The ENV hash maps environmental variable names to their values:
ENV['HOME']
[edit] Slate
Environment variables at: 'PATH'.
"==> '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'"
[edit] Standard ML
OS.Process.getEnv "HOME"
returns an option type which is either SOME value or NONE if variable doesn't exist
[edit] SNOBOL4
Works with: Macro Spitbol Works with: CSnobol
The host(4) function returns a known environment variable.
output = host(4,'PATH')
end
[edit] Tcl
The env global array maps environmental variable names to their values:
$env(HOME)
[edit] UNIX Shell
In Bash, you can use the environment variable like other variables in Bash; for example to print it out, you can do
echo $HOME
In Bash, the "env" command will print out all the key=value pairs to the screen.
[edit] 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'>
[edit] Vedit macro language
Get_Environment(10,"PATH")
Message(@10)
Or with short keywords:
GE(10,"PATH") M(@10)

