FIELD NOTES / UNIX & LINUXNew tools on weekdays. Beyond the man page.
$env

env: give one command the environment you intended

Construct a deliberate child environment, control executable lookup, and preserve enough evidence to diagnose what actually ran.

THE DEEP DIVE14 MIN READ
01

Start with the environment itself

Environment variables are often blamed when a command works in an interactive shell but fails from cron, a service, or an automation runner. The useful response is not to copy the entire login environment. It is to identify which name/value strings the command actually needs, remove the ones it should not inherit, and make executable lookup part of the same decision.

GNU env does two closely related jobs: it constructs an environment and then either prints that environment or starts one command with it. It is a standalone Coreutils program, not a Bash built-in. The environment is an array of strings conventionally shaped like name=value; it is not the command's arguments, working directory, permissions, or filesystem view. Use env when you need to reproduce or diagnose one command's environment without changing the parent shell. We will begin with a small synthetic environment, then make the boundary precise enough to diagnose jobs and review a search path safely.

These examples use GNU Coreutils env 9.4 and Bash 5.2.21 on Linux. POSIX.1-2024 specifies the basic env, -i, assignments, command invocation, and statuses. GNU-only options are identified where they appear.

Run the examples in order in one Bash session. The first block creates and enters a disposable env-lab directory. If that directory already exists, choose another name and rerun the whole block. The && operators run the next step only after success, so a failed mkdir cannot leave later examples writing in the caller's directory. export LC_ALL=C sets the C locale in this shell and its future children, giving the examples stable diagnostics. mkdir creates the directory, and cd changes the current shell's working directory.

The -i option tells env to ignore every inherited environment string. The two name=value operands then add only APP_MODE=audit and a command search path. Because no command follows them, env prints the resulting environment to standard output, one entry per line. The order of a general environment listing is not a portable sorting contract; this controlled GNU 9.4 example shows the two operands in insertion order.

TERMINALGNU COREUTILS AND BASH
export LC_ALL=C &&
mkdir env-lab &&
cd env-lab &&
env -i APP_MODE=audit PATH=/usr/bin:/bin
TERMINALEXPECTED OUTPUT ON GNU 9.4
APP_MODE=audit
PATH=/usr/bin:/bin

An environment entry is one string split conceptually at its first equals sign. APP_MODE is the name and audit is its value. PATH is a colon-separated list that programs such as env can use to locate a command without a slash in its name. This listing contains no host credentials because -i discarded the real inherited environment before printing. Running plain env would print the current process environment, which may include tokens, proxy credentials, or other sensitive values; do not paste an unreviewed dump into a ticket.

02

Change one child without changing its parent

Most administration does not require an entirely clean environment. It requires changing one value for one invocation. export APP_MODE=parent sets a shell variable and marks it for inheritance by later child processes. In the next command, the APP_MODE=audit operand belongs to env; env then starts Bash with that replacement value. Bash's -c option interprets the next quoted string as shell code. Single quotes keep $APP_MODE from expanding in the parent, so the child Bash expands the value it actually received.

The final printf runs in the original shell. In its format, %s inserts the following argument and \n ends the line. Double quotes allow the parent shell to expand its own APP_MODE while keeping the result one argument.

TERMINALGNU COREUTILS AND BASH
export APP_MODE=parent
env APP_MODE=audit bash -c 'printf "child mode: %s\n" "$APP_MODE"'
printf 'parent mode: %s\n' "$APP_MODE"
TERMINALEXPECTED OUTPUT ON GNU 9.4
child mode: audit
parent mode: parent

env evaluates assignment operands from left to right; a later assignment to the same name wins. The first operand without an equals sign is the command. Everything after that command name is an argument to the command, not another env assignment. A child receives a copy of the constructed environment; it cannot rewrite its parent shell's environment.

03

Build a small explicit environment

When reproducing a service or scheduled job, inherited conveniences can hide the missing prerequisite. Start from -i, then add only deliberate values. This command provides a trusted minimal PATH, a synthetic HOME, and LC_ALL=C before starting Bash. An empty environment is not automatically usable: a command without a slash still needs an appropriate PATH for env to find it. Alternatively, use an absolute command path.

Inside the child, ${APP_MODE-unset} is Bash parameter expansion. It substitutes unset only when APP_MODE is absent; unlike the :- form, it does not treat an empty value as absent. The braces identify the variable name, and the hyphen introduces the fallback word.

TERMINALGNU COREUTILS AND BASH
env -i PATH=/usr/bin:/bin HOME=/srv/demo LC_ALL=C \
  bash -c 'printf "PATH=%s\nHOME=%s\nLC_ALL=%s\nAPP_MODE=%s\n" "$PATH" "$HOME" "$LC_ALL" "${APP_MODE-unset}"'
TERMINALEXPECTED OUTPUT ON GNU 9.4
PATH=/usr/bin:/bin
HOME=/srv/demo
LC_ALL=C
APP_MODE=unset

env uses the supplied PATH before it searches for bash. The backslash at the end of the first display line is Bash's line continuation: it removes that newline so this remains one command. A clean environment does not create a sandbox or a standard login session. It merely controls the environment strings supplied to the child.

04

Distinguish an absent value from an empty one

Sometimes a program treats “not configured” differently from “configured as empty.” GNU -u NAME, also accepted as --unset=NAME, removes that name if it exists. This option is not part of the POSIX env interface. The first command inherits TOKEN=visible from the parent but removes it before starting Bash.

${TOKEN+present} expands to present when TOKEN exists, even if its value is empty, and expands to nothing when the name is absent. The second invocation sets TOKEN= to a present but empty value. ${#TOKEN} expands to the number of characters in that value.

TERMINALGNU COREUTILS AND BASH
export TOKEN=visible
env -u TOKEN bash -c 'printf "unset marker: <%s>\n" "${TOKEN+present}"'
env TOKEN= bash -c 'printf "empty marker: <%s>; length=%s\n" "${TOKEN+present}" "${#TOKEN}"'
TERMINALEXPECTED OUTPUT ON GNU 9.4
unset marker: <>
empty marker: <present>; length=0

Use removal when inheritance itself is unwanted. Assign an empty value only when the receiving program documents that empty has the intended meaning. env -u changes the child environment; the exported parent value remains visible in this shell.

05

Change the child's directory, not yours

Environment and working directory are separate process state. GNU -C DIR, also written --chdir=DIR, changes directory before it starts the command. It is a GNU extension, not a POSIX env option.

The setup creates work and writes one newline-terminated fixture file. The shell's > redirection creates or replaces work/item.txt. In the child, ${PWD##*/} removes the longest prefix ending in / from PWD, leaving the last path component. cat copies the fixture to standard output. After the child finishes, the parent applies the same expansion to its own unchanged PWD.

TERMINALGNU COREUTILS AND BASH
mkdir work &&
printf '%s\n' 'fixture data' > work/item.txt &&
env -C work bash -c 'printf "child directory: %s\n" "${PWD##*/}"; printf "%s\n" "child file:"; cat item.txt' &&
printf 'parent directory: %s\n' "${PWD##*/}"
TERMINALEXPECTED OUTPUT ON GNU 9.4
child directory: work
child file:
fixture data
parent directory: env-lab

This is useful when a diagnostic must reproduce both a service's environment and its working directory. It does not change filesystem permissions, choose a new root, or constrain which paths the child can access.

06

Preserve newlines inside values

With ordinary output, one environment entry per line becomes ambiguous when a value itself contains a newline. GNU -0, or --null, terminates each printed entry with a NUL byte instead. A NUL cannot occur inside an environment name or value, so it is an unambiguous boundary.

Bash's $'...' form is ANSI-C quoting: it turns \n into an actual newline before passing the B=line1\nline2 operand to env. The outer env -i builds only two entries, then the absolute /usr/bin/env -0 prints them with NUL terminators. The pipe sends those bytes to od. Its -A n suppresses address labels, -t x1 selects one-byte hexadecimal values, and -v keeps repeated rows visible. The od deep dive explains why this byte view preserves the distinction between a displayed representation and the original bytes.

TERMINALGNU COREUTILS AND BASH
env -i 'A=one two' $'B=line1\nline2' /usr/bin/env -0 |
  od -A n -t x1 -v
TERMINALEXPECTED OUTPUT ON GNU 9.4
 41 3d 6f 6e 65 20 74 77 6f 00 42 3d 6c 69 6e 65
 31 0a 6c 69 6e 65 32 00

Byte 00 ends each environment entry. Byte 0a is the newline inside B; it does not end that entry. NUL-delimited output makes parsing possible, but the data can still be sensitive. Keep it out of logs unless the values are known-safe synthetic data or have been reviewed.

07

Put multiple interpreter arguments in a shebang

The kernel's interpreter line begins with #!, followed by an interpreter path and an optional argument. On Linux, that optional text is passed as one string; it is not generally split into several shell-like arguments. GNU env -S STRING, or --split-string=STRING, splits its one string into separate arguments. This GNU feature is especially useful in a shebang, but it is not in POSIX and is not available on every env implementation.

This block creates an executable script. Each single-quoted argument to the setup printf becomes one literal line, so the parent shell does not expand $MODE or $1 while writing the file. chmod +x adds execute permission. In the shebang, -S splits bash -eu into the command bash and the combined Bash options -e and -u: -e exits after an unhandled command failure, while -u treats an expansion of an unset variable as an error. The invocation supplies both MODE and positional parameter $1.

TERMINALGNU COREUTILS AND BASH
printf '%s\n' \
  '#!/usr/bin/env -S bash -eu' \
  'printf "script mode: %s; argument: %s\n" "$MODE" "$1"' > check-env &&
chmod +x check-env &&
MODE=audit ./check-env sample
TERMINALEXPECTED OUTPUT ON GNU 9.4
script mode: audit; argument: sample

The equals sign belongs to the leading shell assignment, so MODE=audit is present for the script only. The script path begins with ./ because the current directory is not assumed to be in PATH. env then searches the inherited PATH for bash. While troubleshooting, GNU env -v -S STRING can show how the string is split: -v enables verbose diagnostic output, and -S performs the split. That diagnostic output goes to standard error. The path /usr/bin/env is common on Linux, not a universal promise across Unix systems.

08

Audit which executable a path can select

Changing PATH in an env invocation affects how env locates its command. That is useful, and it is also a trust boundary. The setup creates two harmless executable scripts named probe. Their absolute interpreter is /bin/sh; each prints which directory supplied it. chmod +x makes both files invokable.

In the first invocation, shadow comes before trusted in the supplied colon-separated PATH, so env runs shadow/probe. The second invocation provides only the trusted directory. The final invocation names the trusted script with a slash, so env does not perform a PATH search for it.

TERMINALGNU COREUTILS AND BASH
mkdir trusted shadow &&
printf '%s\n' '#!/bin/sh' 'printf "%s\n" "shadow probe"' > shadow/probe &&
printf '%s\n' '#!/bin/sh' 'printf "%s\n" "trusted probe"' > trusted/probe &&
chmod +x shadow/probe trusted/probe &&
env PATH="$PWD/shadow:$PWD/trusted" probe &&
env PATH="$PWD/trusted" probe &&
env PATH="$PWD/shadow" "$PWD/trusted/probe"
TERMINALEXPECTED OUTPUT ON GNU 9.4
shadow probe
trusted probe
trusted probe

This controlled example models an important review question: which writable or unexpected directory wins before a trusted executable? It does not prove that a real system is compromised. For automation or privileged workflows, use a documented minimal search path or absolute executable names, protect the referenced directories, and review the program's own configuration. env performs the requested lookup; it does not decide whether the result is trustworthy.

09

Keep invocation failure separate from child failure

GNU and POSIX reserve status 126 when a command is found but cannot be invoked and 127 when it cannot be found. Other statuses normally come from the command itself; GNU reserves 125 for a failure in env. This block creates a non-executable file named blocked, then asks env to search only the current directory. Standard error is redirected with 2> into diagnostic files so the article does not depend on exact localized wording. blocked_status=$? and missing_status=$? save each status immediately before another command can replace it.

The final child Bash deliberately produces status 7. Bash's exit 7 built-in terminates that child shell and makes 7 its exit status.

TERMINALGNU COREUTILS AND BASH
printf '%s\n' 'not executable' > blocked
env PATH="$PWD" blocked 2> blocked.err
blocked_status=$?
env PATH="$PWD" absent-command 2> missing.err
missing_status=$?
env bash -c 'exit 7'
child_status=$?
printf 'blocked=%s missing=%s child=%s\n' "$blocked_status" "$missing_status" "$child_status"
TERMINALEXPECTED OUTPUT ON GNU 9.4
blocked=126 missing=127 child=7

The capture files prove diagnostics were separated, but their existence does not make a failed command successful. A wrapper should preserve both status and diagnostics, distinguish setup/invocation failures from application results, and avoid assigning a universal meaning to every other nonzero child status.

10

Treat the environment as policy, not containment

env helps make one execution context explicit: inherited names, removed names, deliberate values, working directory, executable lookup, and command arguments. It does not lower privileges, limit memory or file access, block the network, validate executables, or prevent a child from launching descendants. A clean environment is smaller state, not a sandbox.

During authorized administration or assessment, compare the documented service environment with a small synthetic reproduction, inspect whether PATH, locale, proxy, or application-specific settings can redirect behavior, and keep any environment capture under the same controls as credentials. Dynamic loaders and privileged programs may apply additional security rules; do not assume that an environment value will be honored merely because env supplied it.

Before wrapping real work, decide which names may be inherited, which must be removed, which exact values are required, and which directory the command expects. Decide whether command lookup should use a minimal trusted PATH or an absolute name. Capture output and diagnostics deliberately, save the exit status immediately, and remember that a successful env setup says nothing about the correctness or safety of the program it launched. The goal is not a pristine-looking variable list. It is an execution boundary whose assumptions another administrator can inspect.

Back to latest issue
HELP SHAPE THE NEXT ISSUE

What belongs in your toolbox?

Choose a command you want to know better. We start with familiar tools and work toward the less obvious ones.

READER’S CHOICE

What should we cover next?

Vote for a future deep dive, or suggest a command we missed.

One command name, up to 32 characters. Suggestions are reviewed by a person. A new article starts a fresh poll.

Loading poll…