Taskcore
Read an environment variable
Also called get an environment variable, read an env var with a default, getenv.
Read one environment variable of the process, return the value also when it is empty, and return a default only when the variable is not set.
- Evidence
- Code in 10 languages
Task
Read the value of one environment variable of the process. If the variable is not set, use a default value.
Each solution is a function get_env(name, default) that returns a string. It returns the value when the variable is set. It also returns the value when the value is the empty string. It returns default only when the variable is not set.
The rules are those of POSIX. An environment variable is a string name=value, and a name has no =. Upper and lower case letters stay different, so APP_PORT and app_port are two variables. A value can hold any byte except NUL. The cases use UTF-8 values only.
A process gets its environment when it starts. A child process gets a copy of the environment of its parent, so a change in the child does not change the parent.
The tests control the input. Each test sets or removes the variables in its own process before the call. In Java, System.getenv() returns an unmodifiable map, so the Java test starts a child JVM with the environment of each case.
Solutions
Each solution asks the environment for one name, and tells "not set" apart from "set to the empty string".
- Python.
os.environ.get(name, default).os.getenv(name, default)gives the same result. Python copies the environment into theos.environmapping when it importsos. Assignment toos.environchanges both the mapping and the environment. - JavaScript and TypeScript (Node.js).
process.envis an object that holds the environment, and a missing variable givesundefined. The solution tests the name withObject.hasOwn(process.env, name), becauseprocess.envalso inherits properties such astoString. The TypeScript file adds types only. - Java.
System.getenv(name)returnsnullwhen the variable is not set, andObjects.requireNonNullElseputs the default in its place.System.getenv()returns a map of all the variables. - C#.
Environment.GetEnvironmentVariable(name)returnsnullwhen the variable is not found, and??gives the default. - Go.
os.LookupEnv(name)returns the value and a boolean that is true when the variable is present.os.Getenvreturns""when the variable is not present, so it cannot tell missing from empty. - Rust.
env::var(name)returnsErr(VarError::NotPresent)when the variable is not set, andErr(VarError::NotUnicode)when the value is not valid Unicode. The solution changes onlyNotPresentinto the default.env::var_osreturns anOption<OsString>and does not check the value. - C.
getenv(name)returns a null pointer when the variable is not found. The string belongs to the environment, so do not change it. A latersetenv,unsetenvorputenvcan overwrite or free it, so copy the value before you change the environment. - C++.
std::getenvfrom<cstdlib>, with the same rules. The solution copies the value into astd::stringat once. - Bash.
${!name-$default}. The!reads the variable whose name is inname. The-without a colon gives the default only when the variable is unset. At startup Bash makes a shell variable from each environment variable, so this also sees shell variables that are not exported. With a fixed name, write${APP_PORT-80}.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl. Each case gives the variables that the test sets (env), the name and the default.
missing: no variable, so the result is the default.empty-value:APP_MODEis set to"". The result is"", not the default.empty-default: the default can also be the empty string.spaces,equalsandnewline: the value comes back with no change. A name has no=, so each=after the name is part of the value.non-ascii: a UTF-8 value with characters of 2, 3 and 4 bytes.case:APP_PORTis set, and the call asks forapp_port. On POSIX the result is the default. The .NET and Node.js documentation says that on Windows names are not case-sensitive. The Java documentation says that on Windows case is usually not significant. Python on Windows changes the keys ofos.environto upper case.inherited-name: the nametoStringis not set. In JavaScript,process.env[name] ?? defaultValuereturns a function for this name.- Values that are not UTF-8: JSON cannot hold such bytes, so no case file has them. Rust
env::vargivesNotUnicode. On Unix, Python decodes the bytes with thesurrogateescapeerror handler. A Go string holds bytes, so Go returns them with no change. The Rust, Python, Go, C and C++ tests check this.
Pitfalls
- An empty value that counts as missing. Some code uses a second rule: an empty value also gives the default. Bash
${VAR:-default}with a colon follows this rule:
export APP_MODE=
echo "with colon: [${APP_MODE:-production}]"
echo "without colon: [${APP_MODE-production}]"
with colon: [production]
without colon: []
The JavaScript || operator also follows it, because "" is falsy. ?? replaces only null and undefined. The string "0" is not falsy, so || keeps it. The last line shows the inherited toString:
process.env.APP_MODE = "";
process.env.APP_RETRIES = "0";
console.log(JSON.stringify(process.env.APP_MODE || "production"));
console.log(JSON.stringify(process.env.APP_MODE ?? "production"));
console.log(JSON.stringify(process.env.APP_RETRIES || "3"));
console.log(typeof process.env.toString);
"production"
""
"0"
function
In Python, os.environ.get(name) or default follows the second rule, because "" is false. The second rule is correct when an empty value has no use, for example a port number. It is wrong when the empty string is a valid setting, for example an empty prefix. Choose one rule for each variable and write it down.
os.Getenvin Go. It returns""for an empty value and for a missing variable:
package main
import (
"fmt"
"os"
)
func main() {
os.Setenv("APP_MODE", "")
os.Unsetenv("APP_TOKEN")
fmt.Printf("Getenv: %q %q\n", os.Getenv("APP_MODE"), os.Getenv("APP_TOKEN"))
_, modeSet := os.LookupEnv("APP_MODE")
_, tokenSet := os.LookupEnv("APP_TOKEN")
fmt.Println("LookupEnv:", modeSet, tokenSet)
}
Getenv: "" ""
LookupEnv: true false
- A change in a child process. The child changes its own copy of the environment. The parent does not see the change:
unset APP_MODE
bash -c 'export APP_MODE=debug; echo "child: $APP_MODE"'
echo "parent: ${APP_MODE-not set}"
child: debug
parent: not set
- A stale copy in Python.
os.putenvchanges the environment of the process, but notos.environ.os.reload_environreads the environment again. Assign toos.environinstead:
import os
os.environ.pop("APP_MODE", None)
os.putenv("APP_MODE", "debug")
print(os.environ.get("APP_MODE"))
os.environ["APP_MODE"] = "debug"
print(os.environ.get("APP_MODE"))
None
debug
.NET has a similar gap: a change that a native library makes is not seen by managed code.
- A value that is not UTF-8 in Rust.
env::vargivesNotUnicode, notNotPresent. Soenv::var(name).unwrap_or(default)hides a bad value behind the default:
use std::env;
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
fn main() {
// SAFETY: this program has one thread.
unsafe { env::set_var("APP_NAME", OsStr::from_bytes(b"caf\xe9")) };
println!("{:?}", env::var("APP_NAME"));
println!("{:?}", env::var("APP_NAME").unwrap_or("guest".to_string()));
println!("{:?}", env::var_os("APP_NAME"));
}
Err(NotUnicode("caf\xE9"))
"guest"
Some("caf\xE9")
- Changes from other threads. POSIX does not require
setenvto be thread-safe.getenvis thread-safe only while no other thread changes the environment. For this reason, Rustset_varandremove_varareunsafe. Read the variables once, before the program starts threads, and pass the values on. To give a variable to a child process, set it on the child, for example with RustCommand::env.
Related tasks
- Parse command-line arguments: the other input that a program gets when it starts.
- Split a string: split a value such as a list of paths into its parts.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-an-environment-variable/.
import os
def get_env(name: str, default: str) -> str:
"""Return the value of the environment variable name, or default when it is not set.
An empty value is a value, so it does not give the default.
"""
return os.environ.get(name, default)
test_get_env.py 40 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-an-environment-variable/.
import os
import sys
import pytest
from get_env import get_env
# name: (variables to set, name to read, default, expected value)
CASES = {
"present": ({"APP_PORT": "8080"}, "APP_PORT", "80", "8080"),
"path-value": ({"APP_HOME": "/srv/app"}, "APP_HOME", "/opt/app", "/srv/app"),
"missing": ({}, "APP_PORT", "80", "80"),
"empty-value": ({"APP_MODE": ""}, "APP_MODE", "production", ""),
"empty-default": ({}, "APP_MODE", "", ""),
"spaces": ({"APP_TITLE": " two spaces "}, "APP_TITLE", "none", " two spaces "),
"equals": ({"APP_QUERY": "key=value=more"}, "APP_QUERY", "none", "key=value=more"),
"newline": ({"APP_TEXT": "first\nsecond"}, "APP_TEXT", "none", "first\nsecond"),
"non-ascii": ({"APP_GREETING": "xin chào, 日本語, 🙂"}, "APP_GREETING", "none", "xin chào, 日本語, 🙂"),
"case": ({"APP_PORT": "8080"}, "app_port", "80", "80"),
"inherited-name": ({}, "toString", "none", "none"),
}
@pytest.mark.parametrize("case", CASES)
def test_cases(monkeypatch: pytest.MonkeyPatch, case: str) -> None:
env, name, default, want = CASES[case]
monkeypatch.delenv(name, raising=False)
for key, value in env.items():
monkeypatch.setenv(key, value)
assert get_env(name, default) == want
@pytest.mark.skipif(sys.platform == "win32", reason="os.environb exists only on Unix")
def test_value_not_utf8(monkeypatch: pytest.MonkeyPatch) -> None:
# On Unix, a byte that is not UTF-8 becomes a lone surrogate (surrogateescape).
monkeypatch.setitem(os.environb, b"APP_NAME", b"caf\xe9")
assert get_env("APP_NAME", "none") == "caf\udce9"
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
#include "get_env.hpp"
#include <cstdlib>
std::string get_env(const std::string& name, std::string_view default_value) {
// std::getenv returns a null pointer when the variable is not set. The
// string belongs to the environment, so the function copies it at once.
if (const char* value = std::getenv(name.c_str())) {
return value;
}
return std::string(default_value);
}
get_env.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
#pragma once
#include <string>
#include <string_view>
// Returns a copy of the value of the environment variable name, or
// default_value when it is not set. An empty value is a value, so it does not
// give default_value.
std::string get_env(const std::string& name, std::string_view default_value);
test_get_env.cpp 62 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
#include "get_env.hpp"
#include <array>
#include <cstdio>
#include <optional>
#include <print>
#include <string>
#include <utility>
// setenv and unsetenv are POSIX functions in <stdlib.h>.
#include <stdlib.h>
struct Case {
const char* label;
std::optional<std::pair<const char*, const char*>> var; // the variable to set
const char* name;
const char* def;
std::string want;
};
int main() {
const std::array<Case, 12> cases{{
{"present", {{"APP_PORT", "8080"}}, "APP_PORT", "80", "8080"},
{"path-value", {{"APP_HOME", "/srv/app"}}, "APP_HOME", "/opt/app", "/srv/app"},
{"missing", std::nullopt, "APP_PORT", "80", "80"},
{"empty-value", {{"APP_MODE", ""}}, "APP_MODE", "production", ""},
{"empty-default", std::nullopt, "APP_MODE", "", ""},
{"spaces", {{"APP_TITLE", " two spaces "}}, "APP_TITLE", "none", " two spaces "},
{"equals", {{"APP_QUERY", "key=value=more"}}, "APP_QUERY", "none", "key=value=more"},
{"newline", {{"APP_TEXT", "first\nsecond"}}, "APP_TEXT", "none", "first\nsecond"},
{"non-ascii", {{"APP_GREETING", "xin chào, 日本語, 🙂"}}, "APP_GREETING", "none",
"xin chào, 日本語, 🙂"},
{"case", {{"APP_PORT", "8080"}}, "app_port", "80", "80"},
{"inherited-name", std::nullopt, "toString", "none", "none"},
// A std::string holds bytes, so a value that is not UTF-8 comes back unchanged.
{"not-utf8", {{"APP_NAME", "caf\xe9"}}, "APP_NAME", "none", "caf\xe9"},
}};
int failures = 0;
for (const Case& c : cases) {
unsetenv(c.name);
if (c.var && setenv(c.var->first, c.var->second, 1) != 0) {
std::perror("setenv");
return 1;
}
std::string got = get_env(c.name, c.def);
if (got != c.want) {
std::println(stderr, "case {}: got \"{}\", want \"{}\"", c.label, got, c.want);
++failures;
}
if (c.var) {
unsetenv(c.var->first);
}
}
if (failures != 0) {
return 1;
}
std::println("all cases pass");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
import java.util.Objects;
public final class GetEnv {
private GetEnv() {}
/**
* Returns the value of the environment variable name, or defaultValue when it is not set. An
* empty value is a value, so it does not give defaultValue.
*/
public static String getEnv(String name, String defaultValue) {
// System.getenv(name) returns null when the variable is not set.
return Objects.requireNonNullElse(System.getenv(name), defaultValue);
}
}
GetEnvTest.java 68 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
// System.getenv() returns an unmodifiable map. So each case starts a child
// JVM with the environment of the case, and the child calls getEnv.
class GetEnvTest {
/** The child: prints getEnv(args[0], args[1]) as UTF-8, with no line end. */
public static void main(String[] args) throws IOException {
System.out.write(GetEnv.getEnv(args[0], args[1]).getBytes(StandardCharsets.UTF_8));
System.out.flush();
}
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("present", Map.of("APP_PORT", "8080"), "APP_PORT", "80", "8080"),
Arguments.of("path-value", Map.of("APP_HOME", "/srv/app"), "APP_HOME", "/opt/app", "/srv/app"),
Arguments.of("missing", Map.of(), "APP_PORT", "80", "80"),
Arguments.of("empty-value", Map.of("APP_MODE", ""), "APP_MODE", "production", ""),
Arguments.of("empty-default", Map.of(), "APP_MODE", "", ""),
Arguments.of(
"spaces", Map.of("APP_TITLE", " two spaces "), "APP_TITLE", "none", " two spaces "),
Arguments.of(
"equals", Map.of("APP_QUERY", "key=value=more"), "APP_QUERY", "none", "key=value=more"),
Arguments.of(
"newline", Map.of("APP_TEXT", "first\nsecond"), "APP_TEXT", "none", "first\nsecond"),
Arguments.of(
"non-ascii",
Map.of("APP_GREETING", "xin chào, 日本語, 🙂"),
"APP_GREETING",
"none",
"xin chào, 日本語, 🙂"),
Arguments.of("case", Map.of("APP_PORT", "8080"), "app_port", "80", "80"),
Arguments.of("inherited-name", Map.of(), "toString", "none", "none"));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void returnsTheValueOrTheDefault(
String label, Map<String, String> env, String name, String defaultValue, String want)
throws IOException, InterruptedException, URISyntaxException {
String java = ProcessHandle.current().info().command().orElseThrow();
String classes =
Path.of(GetEnvTest.class.getProtectionDomain().getCodeSource().getLocation().toURI())
.toString();
ProcessBuilder pb =
new ProcessBuilder(java, "-cp", classes, "GetEnvTest", name, defaultValue)
.redirectError(Redirect.INHERIT);
pb.environment().remove(name);
pb.environment().putAll(env);
Process child = pb.start();
String got = new String(child.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
assertEquals(0, child.waitFor(), label);
assertEquals(want, got, label);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
#include "get_env.h"
#include <stdlib.h>
const char *get_env(const char *name, const char *default_value) {
// getenv returns a null pointer when the variable is not set.
const char *value = getenv(name);
return value != NULL ? value : default_value;
}
get_env.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
#ifndef GET_ENV_H
#define GET_ENV_H
// get_env returns the value of the environment variable name, or
// default_value when it is not set. An empty value is a value, so it does not
// give default_value. The result points into the environment: do not change
// it, and copy it before a call to setenv, unsetenv or putenv.
const char *get_env(const char *name, const char *default_value);
#endif
test_get_env.c 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
// setenv and unsetenv are POSIX, not ISO C.
#define _POSIX_C_SOURCE 200809L
#include "get_env.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int failures = 0;
// check sets the variable key to value (no variable when key is NULL), unsets
// name if it is a different variable, and compares get_env(name, def) with want.
static void check(const char *label, const char *key, const char *value,
const char *name, const char *def, const char *want) {
unsetenv(name);
if (key != NULL && setenv(key, value, 1) != 0) {
perror("setenv");
exit(1);
}
const char *got = get_env(name, def);
if (strcmp(got, want) != 0) {
fprintf(stderr, "case %s: got \"%s\", want \"%s\"\n", label, got, want);
failures++;
}
if (key != NULL) {
unsetenv(key);
}
}
int main(void) {
check("present", "APP_PORT", "8080", "APP_PORT", "80", "8080");
check("path-value", "APP_HOME", "/srv/app", "APP_HOME", "/opt/app", "/srv/app");
check("missing", NULL, NULL, "APP_PORT", "80", "80");
check("empty-value", "APP_MODE", "", "APP_MODE", "production", "");
check("empty-default", NULL, NULL, "APP_MODE", "", "");
check("spaces", "APP_TITLE", " two spaces ", "APP_TITLE", "none", " two spaces ");
check("equals", "APP_QUERY", "key=value=more", "APP_QUERY", "none", "key=value=more");
check("newline", "APP_TEXT", "first\nsecond", "APP_TEXT", "none", "first\nsecond");
check("non-ascii", "APP_GREETING", "xin chào, 日本語, 🙂", "APP_GREETING", "none",
"xin chào, 日本語, 🙂");
check("case", "APP_PORT", "8080", "app_port", "80", "80");
check("inherited-name", NULL, NULL, "toString", "none", "none");
// A C string holds bytes, so a value that is not UTF-8 comes back unchanged.
check("not-utf8", "APP_NAME", "caf\xe9", "APP_NAME", "none", "caf\xe9");
if (failures != 0) {
return 1;
}
puts("all cases pass");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
public static class Env
{
// Returns the value of the environment variable name, or defaultValue when
// it is not set. An empty value is a value, so it does not give defaultValue.
public static string GetEnv(string name, string defaultValue) =>
// GetEnvironmentVariable returns null when the variable is not set.
Environment.GetEnvironmentVariable(name) ?? defaultValue;
}
EnvTests.cs 47 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
using Xunit;
// xUnit runs the tests of one class one after the other, so the tests can
// change the environment of the process.
public sealed class EnvTests
{
public static TheoryData<string, string?, string?, string, string, string> Cases => new()
{
{ "present", "APP_PORT", "8080", "APP_PORT", "80", "8080" },
{ "path-value", "APP_HOME", "/srv/app", "APP_HOME", "/opt/app", "/srv/app" },
{ "missing", null, null, "APP_PORT", "80", "80" },
{ "empty-value", "APP_MODE", "", "APP_MODE", "production", "" },
{ "empty-default", null, null, "APP_MODE", "", "" },
{ "spaces", "APP_TITLE", " two spaces ", "APP_TITLE", "none", " two spaces " },
{ "equals", "APP_QUERY", "key=value=more", "APP_QUERY", "none", "key=value=more" },
{ "newline", "APP_TEXT", "first\nsecond", "APP_TEXT", "none", "first\nsecond" },
{ "non-ascii", "APP_GREETING", "xin chào, 日本語, 🙂", "APP_GREETING", "none", "xin chào, 日本語, 🙂" },
{ "case", "APP_PORT", "8080", "app_port", "80", "80" },
{ "inherited-name", null, null, "toString", "none", "none" },
};
[Theory]
[MemberData(nameof(Cases))]
public void ReturnsTheValueOrTheDefault(string label, string? key, string? value, string name, string defaultValue, string want)
{
// A null value removes the variable.
Environment.SetEnvironmentVariable(name, null);
if (key is not null)
{
Environment.SetEnvironmentVariable(key, value);
}
try
{
Assert.True(want == Env.GetEnv(name, defaultValue), label);
}
finally
{
if (key is not null)
{
Environment.SetEnvironmentVariable(key, null);
}
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
/**
* Returns the value of the environment variable name, or defaultValue when it is not set.
* An empty value is a value, so it does not give the default.
* @param {string} name
* @param {string} defaultValue
* @returns {string}
*/
export function getEnv(name, defaultValue) {
// process.env inherits from an object, so process.env.toString is a function.
// Object.hasOwn sees only the variables.
return Object.hasOwn(process.env, name) ? process.env[name] : defaultValue;
}
getEnv.test.js 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { getEnv } from "./getEnv.js";
// [case, variables to set, name to read, default, expected value]
const cases = [
["present", { APP_PORT: "8080" }, "APP_PORT", "80", "8080"],
["path-value", { APP_HOME: "/srv/app" }, "APP_HOME", "/opt/app", "/srv/app"],
["missing", {}, "APP_PORT", "80", "80"],
["empty-value", { APP_MODE: "" }, "APP_MODE", "production", ""],
["empty-default", {}, "APP_MODE", "", ""],
["spaces", { APP_TITLE: " two spaces " }, "APP_TITLE", "none", " two spaces "],
["equals", { APP_QUERY: "key=value=more" }, "APP_QUERY", "none", "key=value=more"],
["newline", { APP_TEXT: "first\nsecond" }, "APP_TEXT", "none", "first\nsecond"],
["non-ascii", { APP_GREETING: "xin chào, 日本語, 🙂" }, "APP_GREETING", "none", "xin chào, 日本語, 🙂"],
["case", { APP_PORT: "8080" }, "app_port", "80", "80"],
["inherited-name", {}, "toString", "none", "none"],
];
for (const [name, env, key, defaultValue, want] of cases) {
test(name, () => {
const saved = { ...process.env };
try {
delete process.env[key];
Object.assign(process.env, env);
assert.equal(getEnv(key, defaultValue), want);
} finally {
for (const k of Object.keys(process.env)) if (!Object.hasOwn(saved, k)) delete process.env[k];
Object.assign(process.env, saved);
}
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
// Returns the value of the environment variable name, or defaultValue when it is not set.
// An empty value is a value, so it does not give the default.
export function getEnv(name: string, defaultValue: string): string {
// process.env inherits from an object, so process.env.toString is a function.
// Object.hasOwn sees only the variables.
const value = Object.hasOwn(process.env, name) ? process.env[name] : undefined;
return value ?? defaultValue;
}
getEnv.test.ts 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { getEnv } from "./getEnv.ts";
// [case, variables to set, name to read, default, expected value]
const cases: [string, Record<string, string>, string, string, string][] = [
["present", { APP_PORT: "8080" }, "APP_PORT", "80", "8080"],
["path-value", { APP_HOME: "/srv/app" }, "APP_HOME", "/opt/app", "/srv/app"],
["missing", {}, "APP_PORT", "80", "80"],
["empty-value", { APP_MODE: "" }, "APP_MODE", "production", ""],
["empty-default", {}, "APP_MODE", "", ""],
["spaces", { APP_TITLE: " two spaces " }, "APP_TITLE", "none", " two spaces "],
["equals", { APP_QUERY: "key=value=more" }, "APP_QUERY", "none", "key=value=more"],
["newline", { APP_TEXT: "first\nsecond" }, "APP_TEXT", "none", "first\nsecond"],
["non-ascii", { APP_GREETING: "xin chào, 日本語, 🙂" }, "APP_GREETING", "none", "xin chào, 日本語, 🙂"],
["case", { APP_PORT: "8080" }, "app_port", "80", "80"],
["inherited-name", {}, "toString", "none", "none"],
];
for (const [name, env, key, defaultValue, want] of cases) {
test(name, () => {
const saved = { ...process.env };
try {
delete process.env[key];
Object.assign(process.env, env);
assert.equal(getEnv(key, defaultValue), want);
} finally {
for (const k of Object.keys(process.env)) if (!Object.hasOwn(saved, k)) delete process.env[k];
Object.assign(process.env, saved);
}
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
// Package getenv reads an environment variable with a default.
package getenv
import "os"
// GetEnv returns the value of the environment variable name, or def when it
// is not set. An empty value is a value, so it does not give def.
func GetEnv(name, def string) string {
// os.Getenv returns "" for both a missing and an empty variable.
// LookupEnv tells the two apart.
if value, ok := os.LookupEnv(name); ok {
return value
}
return def
}
get_env_test.go 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
package getenv
import (
"os"
"testing"
)
func TestCases(t *testing.T) {
cases := []struct {
name string
env map[string]string
key, def string
want string
}{
{"present", map[string]string{"APP_PORT": "8080"}, "APP_PORT", "80", "8080"},
{"path-value", map[string]string{"APP_HOME": "/srv/app"}, "APP_HOME", "/opt/app", "/srv/app"},
{"missing", nil, "APP_PORT", "80", "80"},
{"empty-value", map[string]string{"APP_MODE": ""}, "APP_MODE", "production", ""},
{"empty-default", nil, "APP_MODE", "", ""},
{"spaces", map[string]string{"APP_TITLE": " two spaces "}, "APP_TITLE", "none", " two spaces "},
{"equals", map[string]string{"APP_QUERY": "key=value=more"}, "APP_QUERY", "none", "key=value=more"},
{"newline", map[string]string{"APP_TEXT": "first\nsecond"}, "APP_TEXT", "none", "first\nsecond"},
{"non-ascii", map[string]string{"APP_GREETING": "xin chào, 日本語, 🙂"}, "APP_GREETING", "none", "xin chào, 日本語, 🙂"},
{"case", map[string]string{"APP_PORT": "8080"}, "app_port", "80", "80"},
{"inherited-name", nil, "toString", "none", "none"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
// t.Setenv restores the old value at the end of the test.
t.Setenv(c.key, "")
if err := os.Unsetenv(c.key); err != nil {
t.Fatal(err)
}
for k, v := range c.env {
t.Setenv(k, v)
}
if got := GetEnv(c.key, c.def); got != c.want {
t.Errorf("GetEnv(%q, %q) = %q, want %q", c.key, c.def, got, c.want)
}
})
}
}
// A Go string holds bytes, so a value that is not UTF-8 comes back unchanged.
func TestValueNotUTF8(t *testing.T) {
t.Setenv("APP_NAME", "caf\xe9")
if got := GetEnv("APP_NAME", "none"); got != "caf\xe9" {
t.Errorf("GetEnv = %q", got)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
//! Read an environment variable with a default.
use std::env::{self, VarError};
/// Returns the value of the environment variable `name`, or `default` when it is not set.
///
/// An empty value is a value, so it does not give `default`.
/// A value that is not valid Unicode gives `VarError::NotUnicode`.
pub fn get_env(name: &str, default: &str) -> Result<String, VarError> {
match env::var(name) {
Err(VarError::NotPresent) => Ok(default.to_owned()),
other => other,
}
}
tests/get_env_test.rs 88 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/read-an-environment-variable/.
use std::env::{self, VarError};
use algo_read_an_environment_variable::get_env;
// set_var and remove_var are unsafe, because another thread can read the
// environment at the same time. The test harness runs the tests of a file on
// many threads, so this file has one test, and it changes the environment
// only from that test.
#[test]
fn cases() {
let cases: [(&str, &[(&str, &str)], &str, &str, &str); 11] = [
("present", &[("APP_PORT", "8080")], "APP_PORT", "80", "8080"),
(
"path-value",
&[("APP_HOME", "/srv/app")],
"APP_HOME",
"/opt/app",
"/srv/app",
),
("missing", &[], "APP_PORT", "80", "80"),
(
"empty-value",
&[("APP_MODE", "")],
"APP_MODE",
"production",
"",
),
("empty-default", &[], "APP_MODE", "", ""),
(
"spaces",
&[("APP_TITLE", " two spaces ")],
"APP_TITLE",
"none",
" two spaces ",
),
(
"equals",
&[("APP_QUERY", "key=value=more")],
"APP_QUERY",
"none",
"key=value=more",
),
(
"newline",
&[("APP_TEXT", "first\nsecond")],
"APP_TEXT",
"none",
"first\nsecond",
),
(
"non-ascii",
&[("APP_GREETING", "xin chào, 日本語, 🙂")],
"APP_GREETING",
"none",
"xin chào, 日本語, 🙂",
),
("case", &[("APP_PORT", "8080")], "app_port", "80", "80"),
("inherited-name", &[], "toString", "none", "none"),
];
for (case, vars, name, default, want) in cases {
// SAFETY: no other thread reads or writes the environment now.
unsafe { env::remove_var(name) };
for &(key, value) in vars {
unsafe { env::set_var(key, value) };
}
assert_eq!(get_env(name, default), Ok(want.to_owned()), "case {case}");
for &(key, _) in vars {
unsafe { env::remove_var(key) };
}
}
// A value that is not UTF-8 is an error, not the default.
#[cfg(unix)]
{
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let bytes = OsStr::from_bytes(b"caf\xe9");
unsafe { env::set_var("APP_NAME", bytes) };
assert_eq!(
get_env("APP_NAME", "none"),
Err(VarError::NotUnicode(bytes.to_owned()))
);
unsafe { env::remove_var("APP_NAME") };
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-an-environment-variable/.
# get_env NAME DEFAULT
# Prints the value of the variable NAME, or DEFAULT when NAME is not set.
# An empty value is a value, so it does not give DEFAULT.
get_env() {
local name=$1 default=$2
# ${!name} reads the variable whose name is in $name.
# "-" without ":" gives the default only for an unset variable.
printf '%s' "${!name-$default}"
}
test_get_env.bats 37 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/read-an-environment-variable/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/get_env.sh"
}
check() { # check NAME DEFAULT WANT [KEY=VALUE]
local name=$1 default=$2 want=$3
unset -v "$name"
if (($# > 3)); then export "$4"; fi
run get_env "$name" "$default"
[ "$status" -eq 0 ]
[ "$output" = "$want" ]
}
@test "present" { check APP_PORT 80 8080 APP_PORT=8080; }
@test "path-value" { check APP_HOME /opt/app /srv/app APP_HOME=/srv/app; }
@test "missing" { check APP_PORT 80 80; }
@test "empty-value" { check APP_MODE production "" APP_MODE=; }
@test "empty-default" { check APP_MODE "" ""; }
@test "spaces" { check APP_TITLE none " two spaces " "APP_TITLE= two spaces "; }
@test "equals" { check APP_QUERY none key=value=more APP_QUERY=key=value=more; }
@test "newline" { check APP_TEXT none $'first\nsecond' $'APP_TEXT=first\nsecond'; }
@test "non-ascii" { check APP_GREETING none "xin chào, 日本語, 🙂" "APP_GREETING=xin chào, 日本語, 🙂"; }
@test "case" { check app_port 80 80 APP_PORT=8080; }
@test "inherited-name" { check toString none none; }
@test "the value comes from the environment of the process" {
unset -v APP_PORT
run env APP_PORT=8080 bash -c 'source "$1"; get_env APP_PORT 80' _ "$BATS_TEST_DIRNAME/get_env.sh"
[ "$status" -eq 0 ]
[ "$output" = 8080 ]
}
References
- The Open Group, POSIX.1-2024, Base Definitions, Chapter 8, Environment Variables, 8.1 Environment Variable Definition
- The Open Group, POSIX.1-2024, getenv, secure_getenv, Description, Return Value, Rationale, Change History
- The Open Group, POSIX.1-2024, setenv, Description, Errors
- The Python Standard Library, os, Miscellaneous operating system interfaces, os.environ, os.environb, os.reload_environ, os.getenv, os.putenv
- The Python Standard Library, Built-in Types, Truth Value Testing
- Node.js documentation, Process, process.env
- MDN Web Docs, Logical OR (||), Description
- MDN Web Docs, Nullish coalescing operator (??)
- Java SE 25 API, java.lang.System, getenv(String), getenv()
- .NET API reference, Environment.GetEnvironmentVariable, GetEnvironmentVariable(String), Returns, Remarks
- .NET API reference, Environment.SetEnvironmentVariable, SetEnvironmentVariable(String, String), Remarks
- Go standard library, package os, Getenv, LookupEnv
- The Go Programming Language Specification, String types
- The Rust Standard Library, std::env::var, Errors
- The Rust Standard Library, std::env::var_os
- The Rust Standard Library, std::env::set_var, Safety
- cppreference.com, std::getenv
- GNU Bash Reference Manual, Shell Parameter Expansion, 3.5.3, indirect expansion, ${parameter:-word}
- GNU Bash Reference Manual, Environment, 3.7.4
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
The native tests pass in 9 of 10 languages in this build.
Tag T0ZXFQ Edit this page History Report an error Markdown