Environment variables

From Rosetta Code
Jump to: navigation, search
Task
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.

Contents

[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] 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;

[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] 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

[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] 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%

[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] 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
.

[edit] CoffeeScript

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

[edit] 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");
}

[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")
Works with: CLISP
(getenv "HOME")

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

[edit] Delphi/Pascal

program EnvironmentVariable;
 
{$APPTYPE CONSOLE}
 
uses SysUtils;
 
begin
WriteLn('Temp = ' + GetEnvironmentVariable('TEMP'));
end.

[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] Erlang

 
os:getenv( "HOME" ).
 

[edit] Euphoria

puts(1,getenv("PATH"))

[edit] F#

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

[edit] Factor

"HOME" os-env print

[edit] Forth

Works with: GNU Forth
s" HOME" getenv type

[edit] 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

[edit] FunL

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

[edit] 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

[edit] Groovy

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

[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

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

[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] Julia

ENV["HOME"]

[edit] K

_getenv "HOME"

[edit] 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

[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] 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

[edit] Lua

print( os.getenv( "PATH" ) )

[edit] Maple

getenv("PATH");

[edit] Mathematica

Environment["PATH"]

[edit] MATLAB / Octave

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

[edit] 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)
).

[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] 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
. . .

[edit] NewLISP

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

[edit] Nimrod

import os
echo getEnv("HOME")

[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] 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

[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] Prolog

SWI-Prolog has the built in function getenv.

 ?- getenv('TEMP', Temp).

[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] Racket

 
#lang racket
(getenv "HOME")
 

[edit] REBOL

print get-env "HOME"

[edit] Retro

here "HOME" getEnv
here puts

[edit] 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.

[edit] Ruby

The ENV hash maps environment variable names to their values:

ENV['HOME']

[edit] 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$
Output:
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

[edit] Scala

Library: Scala
object Environment_variables extends App {
 
def variablesToUse = Seq("USERPROFILE", "java.library.path", "PATH", "HOME", "HOMEPATH", "USERNAME")
println(sys.env.filter(p => variablesToUse contains p._1).toMap.mkString("\n"))
println
println (System.getProperty("java.library.path").split(";").mkString("\n"))
 
}

[edit] 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;

[edit] Slate

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

[edit] 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.
 

[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] 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.

[edit] 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.

[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)

[edit] 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

[edit] zkl

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

Variants
Actions
Community
Explore
Misc
Toolbox