Shell, system, and network tools

Linux commands: printenv

Learn how the Linux printenv command prints all of your environment variables, or just one like PATH when you pass its name as an argument.

printenv prints the values of your environment variables. That’s its whole job, and it does it well.

In any shell there are a good number of environment variables, set either by the system, or by your own shell scripts and configuration. They are how a process receives its settings: where your home folder is, where to look for programs, which editor to launch. Every command you run inherits them.

You can print them all with the printenv command. The output will be something like this:

HOME=/Users/flavio
LOGNAME=flavio
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin
PWD=/Users/flavio
SHELL=/usr/local/bin/fish

with a few more lines, usually. On a machine with lots of tools installed the list gets long, and printenv | sort makes it easier to scan.

You can pass a variable name as a parameter, to only show that value:

printenv PATH

Terminal showing printenv PATH command output displaying the PATH environment variable value

If the variable does not exist, printenv prints nothing and exits with a non-zero status. You can check that with echo $?, which shows the exit status of the last command:

printenv NOPE
echo $?
# 1

That makes it usable in scripts as a test for whether a variable is set.

Shell variables are not environment variables

Here is the trap that catches everyone once. A variable you assign in the shell is not automatically part of the environment:

MYVAR=test
printenv MYVAR
# nothing printed

MYVAR is a shell variable. Your current shell knows it, and echo $MYVAR shows it. But child processes, printenv included, never receive it. To promote it to an environment variable, use export:

export MYVAR=test
printenv MYVAR
# test

So when a program “can’t see” a variable you are sure you set, check with printenv first. If it’s missing there, the missing piece is the export. I’ve debugged that exact problem more times than I’d like to admit, and printenv finds it in a second.

The printenv command works on Linux, macOS, WSL, and anywhere you have a UNIX environment.

Lesson completed