← All commands
THE COMMAND REFERENCE

env

Run a command with a changed environment, or print the environment.

Last updated

Portable / common

Implementation-level reference; examples are not certified for every installed version.

Overview

env runs a program with changes to its environment variables: add or override some with NAME=value, remove one with -u, or start from nothing with -i. With no command it prints every variable. It is also the portable way to find an interpreter in a script's first line, as in #!/usr/bin/env python3.

Background

The env command appeared in 4.4BSD, according to the macOS manual, which also says it conforms to POSIX.1-2001 and that -u is a non-standard extension. Today the name covers GNU env, the env that macOS ships, and the env applet in BusyBox. They agree on NAME=value, -i and -u.

Examples

Run a command with one extra variable; the change lasts only for that command:

env FOO=bar sh -c 'echo "$FOO"'

Start with an empty environment except for what you give, with -i; env then prints just that one variable:

env -i FOO=bar env

Remove a variable for one command with -u:

HOME=/x env -u HOME sh -c 'echo ${HOME:-unset}'

Print the environment and count the line that holds PATH:

env | grep -c '^PATH='

Options

-i
Start with an empty environment, ignoring the one the shell passed down.

-u
Remove this variable from the environment of the command.

Common mistakes

env FOO=bar with no command only prints the environment with that change, it does not set FOO in your shell; use export FOO=bar for that. -i also removes PATH, so a command may no longer be found; give a full path or set PATH again. A variable set on the command line of your shell before a program, as in FOO=bar prog, does the same thing as env FOO=bar prog for external programs.

Portability

Only NAME=value, -i and -u are in the Common examples. GNU adds -S and -C, and macOS adds -P and -S in its own form, so avoid them in portable scripts. The Common examples were executed on GNU coreutils 9.11, macOS system tools, and BusyBox 1.37.0 (see the development guide for the exact check).

References

Original explanations, with upstream documentation for further reading. FreeBSD references are comparison material, not a claim of Apple version equivalence.