How to get an environment variable?

How to get the value (string) of an environment variable?

asked Mar 31 by zma (2,200 points)

5 Answers

In Go, to get an environment variable (e.g. "VAR"):

import "os"
import "fmt"

fmt.Println("VAR:", os.Getenv("VAR"))

Reference: https://www.systutorials.com/qa/2384/how-to-get-an-environment-variable-in-go

answered Mar 31 by zma (2,200 points)

In C or C++ on Linux,

To get value of an environment variable:

#include <stdlib.h> 

char *getenv(const char *name); 

Reference: https://www.systutorials.com/qa/478/how-to-set-and-get-an-environment-variable-in-c-on-linux

answered Mar 31 by zma (2,200 points)

In Bash, just directly use:

$VAR

Note that if you assigned a value to the "local" variable $VAR in your program before reading the "environmental" $VAR, the $VAR will actually contain the value you assigned.

answered Mar 31 by zma (2,200 points)

In Python, all environment variables can be accessed directly through os.environ

import os
print os.environ['HOME']

If the environment variable is not present, it will raise a KeyError.

You can use get to return None if the environment variable is not present:

print os.environ.get('ENV_MIGHT_EXIST')

os.getenv() is a handy function. It can give a default value instead or None

# return the default value if the environment variable is not present
print os.getenv('ENV_MIGHT_EXIST', 'ENV_DEFAULT_VAL')

# return `None` if the environment variable is not present
print os.getenv('ENV_MIGHT_EXIST')
answered Apr 20 by zma (2,200 points)
edited Apr 20 by zma

You may call the System.getenv(name) library function in Java to get the environment variable value.

public static String getenv(String name)

Parameters:
name - the name of the environment variable

Returns:
the string value of the variable, or null if the variable is not defined in the system environment

One example, in the Java REPL:

java> System.getenv("JAVA_HOME")
java.lang.String res0 = "/usr/java/default/"
answered Apr 22 by zma (2,200 points)

Please log in or register to answer this question.

Related questions

0 answers
4 answers
5 answers
7 answers
asked Mar 31 by zma (2,200 points)
0 answers
Welcome to Do This In Various Langs (dtivl), where you can ask questions and receive solutions in various programming languages.
Copyright © SysTutorials. User contributions licensed under cc-wiki with attribution required.
Hosted on Dreamhost

...