LinuxCommandLibrary
GitHubF-DroidGoogle Play Store

env

run programs with modified environment variables

TLDR

Show all environment variables
$ env
copy
Run command with environment
$ env VAR=value [command]
copy
Clear environment
$ env -i [command]
copy
Unset variable
$ env -u [VAR] [command]
copy

SYNOPSIS

env [options] [VAR=value]... [command]

DESCRIPTION

env runs a program in a modified environment. It can display current environment variables, set new ones, unset existing ones, or run commands with a clean environment.The command is useful for setting variables temporarily or debugging environment issues.

PARAMETERS

-i, --ignore-environment

Start with empty environment
-u var, --unset=var
Remove variable from environment
-0, --null
End lines with NUL, not newline
-C dir, --chdir=dir
Change directory before running command
-S string
Process and split string into arguments (useful in shebang lines)
-v, --verbose
Print verbose information for each processing step

WORKFLOW

$ # Display all environment variables
env

# Set variable for one command
env DEBUG=1 ./program

# Multiple variables
env VAR1=value1 VAR2=value2 command

# Clear environment
env -i command

# Clean environment with specific variables
env -i PATH=/usr/bin HOME=/home/user command

# Unset variable
env -u DISPLAY command

# Change directory first
env -C /tmp ls

# In shebang for portability
#!/usr/bin/env python3
copy

COMMON USES

Shebang lines:

$ #!/usr/bin/env bash
#!/usr/bin/env python3
#!/usr/bin/env node
copy
Temporary variables:
$ env NODE_ENV=production npm start
env DATABASE_URL=postgres://... rails console
copy
Clean environment:
$ env -i PATH="$PATH" command
copy
Debugging:
$ env | grep PATH
env | sort
copy

VARIABLE FORMAT

Variables shown as:

$ NAME=value
PATH=/usr/bin:/bin
HOME=/home/user
copy

COMPARISON WITH EXPORT

env

Runs command with modified environment
export
Sets variables for current shell and children
$ # env (one command only)
env VAR=value command

# export (persistent)
export VAR=value
command  # VAR is available
copy

CAVEATS

Variables set with env don't persist after command exits. Shell built-ins (like `cd`, `alias`) cannot be run via env since it uses `execvp`. When using `-i`, PATH must be explicitly set for commands to be found. Values containing spaces must be quoted. The `-C` and `-S` options are GNU extensions not available on all platforms.

HISTORY

env has been part of Unix since the early days, included in POSIX standards for environment manipulation.

SEE ALSO

export(1), printenv(1), set(1)

Copied to clipboard
Kai