Linux commands
Browse topics

Controlling environment variables with env

Version
unversioned
Review
Draft

Summary#

Every process receives environment variables from its parent. env prints them or runs a command with a changed set.

Syntax#

sh
env
printenv HOME
LOG_LEVEL=debug ./server
env -u HTTP_PROXY ./client
env -i PATH=/usr/bin:/bin ./job
export LOG_LEVEL=debug

An assignment before a command applies to that command only. export makes a shell variable available to later commands. -u removes a variable and -i starts with an empty environment.

Example#

sh
(
  set -eu
  GREETING=local
  sh -c 'echo "child sees: ${GREETING-nothing}"'
  GREETING=once printenv GREETING
  export GREETING
  sh -c 'echo "child sees: ${GREETING-nothing}"'
  env -u GREETING sh -c 'echo "after -u: ${GREETING-nothing}"'
  env -i ONLY=1 /usr/bin/env
)

Expected output#

Text
child sees: nothing
once
child sees: local
after -u: nothing
ONLY=1

Common mistakes#

A variable assigned without export stays in the shell and child processes do not see it, unless it was already exported. A child cannot change its parent's environment, so running a script does not set variables in your shell; source it instead. Environment variables are readable by the process's user and often appear in debug output, so take care with secrets. The example fails to show an unset variable if GREETING is already exported before it starts.

Version applicability#

This entry describes env and printenv from GNU Coreutils.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0