Read Environment Variables in C with getenv
getenv returns a pointer to a variable's value, or NULL when it is unset. Check for NULL, tell empty from unset, copy what you keep and parse numbers safely.

The environment is how a shell, a service manager or a parent program configures your program without touching its command line: HOME says where the user lives, TZ picks a time zone, LINECOUNT_VERBOSE turns on debug output. In C you read it with getenv(), a function with one argument and three behaviors that catch beginners. It returns NULL for a variable that is not set, a pointer into the environment's own memory for one that is, and the same empty string for a variable set to nothing. This post shows the smallest correct program, a helper that supplies defaults, the way to parse numbers and booleans from the environment and the mistakes worth avoiding. It uses C17, GCC 14 and glibc 2.40 on Linux 6.12, and follows getenv(3) and POSIX.1-2024. The wider picture of how the environment reaches a program is in the complete guide to program startup.
The call
#include <stdlib.h>
char *getenv(const char *name);name is the variable name without an equals sign, for example "HOME". If the environment has an entry HOME=/home/dana, the function returns a pointer to the characters after the equals sign, /home/dana. If there is no such entry, it returns NULL. Names are case-sensitive: home and HOME are different variables, and getenv("home") returns NULL on Linux when only HOME exists.
The return type is char *, not const char *, for historical reasons. Treat it as const char * anyway: the standard says the program must not modify the string, because it lives in the environment itself.
The smallest correct program
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
const char *home = getenv("HOME");
if (home == NULL) {
fprintf(stderr, "HOME is not set\n");
return 1;
}
printf("home directory: %s\n", home);
return 0;
}Build it with gcc -std=c17 -Wall -o show_home show_home.c. Run it normally, then with an empty environment using env -i, which starts a program with no variables at all:
./show_home
env -i ./show_homehome directory: /home/dana
HOME is not setThe second run is the reason to test for NULL every time. A program started by cron, by a systemd unit without Environment=, by a container with a stripped environment, or by a test harness often has a small environment that lacks variables your interactive shell sets. Passing NULL to printf("%s") is undefined behavior; glibc prints (null), other systems crash.
Empty is not the same as unset
getenv() distinguishes the two states, and many programs should too. A variable that is set to an empty value returns a pointer to a string of length zero, not NULL:
#include <stdio.h>
#include <stdlib.h>
static void show(const char *name)
{
const char *v = getenv(name);
if (v == NULL)
printf("%-8s unset\n", name);
else if (v[0] == '\0')
printf("%-8s set but empty\n", name);
else
printf("%-8s = %s\n", name, v);
}
int main(void)
{
show("MODE");
show("COLOR");
show("EDITOR");
return 0;
}env -i MODE= COLOR=always ./empty_vs_unsetMODE set but empty
COLOR = always
EDITOR unsetWhich state means what is a design decision for your program. The common convention for on/off switches is that "set to anything" means on and "unset" means off, but some variables are specified differently: NO_COLOR disables color only when it is present and not empty. Decide, document it, and implement it with an explicit check rather than a bare if (getenv(name)), which treats an empty value as true.
A helper with a default
Most configuration reads look like "use this variable, or fall back to a default". A tiny helper keeps the NULL check in one place:
#ifndef ENV_UTIL_H
#define ENV_UTIL_H
#include <stdlib.h>
/* Value of the variable, or fallback when it is unset or empty. */
static inline const char *env_or(const char *name, const char *fallback)
{
const char *v = getenv(name);
return (v != NULL && v[0] != '\0') ? v : fallback;
}
#endif#include <stdio.h>
#include "env_util.h"
int main(void)
{
printf("shell : %s\n", env_or("SHELL", "/bin/sh"));
printf("tmpdir: %s\n", env_or("TMPDIR", "/tmp"));
return 0;
}env -i SHELL=/bin/zsh ./configshell : /bin/zsh
tmpdir: /tmpenv_or() treats empty as unset, which is what most "path or directory" variables need: an empty TMPDIR is never a useful directory. The returned pointer still belongs to the environment, so the same lifetime rules apply, covered next.
The pointer is borrowed
getenv() does not copy. The pointer points into storage that the C library owns, and it can become invalid when the environment changes. A later setenv() or unsetenv() in the same program may overwrite or free the string, and then the pointer you kept dangles. The fix is to copy the value when you need to keep it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
const char *raw = getenv("USER");
char *user = raw ? strdup(raw) : NULL; /* own a copy */
setenv("USER", "someone-else", 1); /* may invalidate raw */
printf("original user was: %s\n", user ? user : "(unset)");
free(user);
return 0;
}env -i USER=dana ./copy_valueoriginal user was: danaReading raw after the setenv() call would be undefined; reading the copy is safe. In a program that never modifies its own environment the borrowed pointer is fine for as long as you like, but in a library you do not know that, so a library function that stores a value for later should strdup() it.
Numbers and flags
Every environment value is a string. Turning it into a number deserves the same care as a command-line argument: use strtol(), check where it stopped and check the range.
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int env_int(const char *name, int fallback)
{
const char *text = getenv(name);
if (text == NULL || *text == '\0')
return fallback;
char *end;
errno = 0;
long v = strtol(text, &end, 10);
if (*end != '\0' || errno == ERANGE || v < 0 || v > 65535)
return fallback; /* malformed: use the default */
return (int)v;
}
static int env_flag(const char *name)
{
const char *v = getenv(name);
if (v == NULL)
return 0;
return strcmp(v, "0") != 0 && strcmp(v, "false") != 0 && v[0] != '\0';
}
int main(void)
{
printf("PORT = %d\n", env_int("PORT", 8080));
printf("DEBUG = %d\n", env_flag("DEBUG"));
return 0;
}env -i PORT=9000 DEBUG=false ./env_numbers
env -i PORT=nine DEBUG=1 ./env_numbersPORT = 9000
DEBUG = 0
PORT = 8080
DEBUG = 1env_int() falls back silently on garbage, which is gentle and can hide a typo. For a service, print a warning on the malformed case so the operator learns that PORT=nine was ignored. atoi() would have returned 0 for nine, and the program would have tried to listen on port 0, which is almost never intended.
Splitting a list variable
Some variables hold a list separated by colons, such as PATH. getenv() returns the whole string, and splitting it is your job. Never call strtok() on the returned pointer, since it writes into the string and corrupts the environment; copy first.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
const char *path = getenv("PATH");
if (!path)
return 1;
char *copy = strdup(path);
int n = 0;
for (char *dir = strtok(copy, ":"); dir; dir = strtok(NULL, ":"))
printf("%d: %s\n", ++n, dir);
free(copy);
return 0;
}env -i PATH=/usr/local/bin:/usr/bin:/bin ./split_path1: /usr/local/bin
2: /usr/bin
3: /binstrtok() skips empty fields, which on a real PATH means it ignores an empty entry that the shell treats as the current directory. If that distinction matters, split with strchr() instead.
Mistakes to avoid
Using the result without a
NULLtest, which crashes in a minimal environment.Writing through the pointer or passing it to
strtok(), which damages the environment.Holding the pointer across a
setenv()call, which can leave it dangling.Calling
getenv()for a secret and printing it in an error message, which sends it to logs.Trusting the environment in a program that runs with more privilege than its caller; use
secure_getenv()there, covered in its own post.Calling
getenv()from one thread while another callssetenv(), which is a data race.
Variables that programs commonly read
Knowing which variables exist saves you from inventing names. Some are conventions every Unix program shares, and following them makes your program behave like its neighbors:
| Variable | Convention |
|---|---|
HOME | The user's home directory; fall back to the password database with getpwuid() when it is unset |
USER, LOGNAME | The login name; not authoritative, since the user can change them |
PATH | Colon-separated directories searched for commands |
TMPDIR | Where to create temporary files; default to /tmp |
LANG, LC_ALL, LC_* | Locale selection, read by setlocale(LC_ALL, "") and not by your own code |
TZ | Time zone, read by localtime() and tzset() |
EDITOR, VISUAL | The user's preferred text editor |
NO_COLOR | Disable color output when present and not empty |
XDG_CONFIG_HOME, XDG_RUNTIME_DIR | Base directories from the XDG specification; fall back to ~/.config for the first |
A good rule is to read a standard variable only when the standard says what it means, and to name your own with a prefix that is yours alone. When a variable is a security-relevant input, such as TMPDIR or HOME in a privileged program, do not read it with getenv() at all: the earlier posts on secure mode explain why.
Testing code that reads the environment
Environment-dependent code is easy to test if you design for it. Pass the lookup in as a function pointer or a plain argument instead of calling getenv() deep inside the logic, so a test supplies its own values:
typedef const char *(*env_lookup_fn)(const char *name);
static int config_port(env_lookup_fn lookup)
{
const char *text = lookup("PORT");
return text ? atoi(text) : 8080;
}A test then passes a lookup that returns canned strings and checks the result, and production code passes getenv. When you cannot change the code, set the variable in the test with setenv() before the call and restore it after, and run such tests single-threaded, because the environment is process-global state. From the shell, env -i NAME=value ./program is the quickest way to run a program under an exact, tiny environment, and env -u NAME ./program runs it with one variable removed.


