🎁 New User? Get 20% off your first purchase with code NEWUSER20 Register Now →
Menu

Categories

printenv Command

Beginner Shell Scripting man(1)

Print all or specific environment variables

👁 10 views 📅 Updated: Mar 15, 2026
SYNTAX
printenv [VARIABLE]...

What Does printenv Do?

printenv prints the values of environment variables. Without arguments, it prints all environment variables. With a variable name as argument, it prints just that variable\'s value.

printenv is simpler than env for displaying variables. It is useful in scripts for checking if a variable is set and getting its value. Unlike echo $VAR, printenv returns a non-zero exit code if the variable is not set.

printenv only shows environment variables (exported), not local shell variables. Use set or declare to see all shell variables.

Options & Flags

OptionDescriptionExample
VARNAME Print value of specific variable printenv HOME
(no args) Print all environment variables printenv
-0 End each line with NUL instead of newline printenv -0
multiple Print multiple specific variables printenv HOME PATH USER

Practical Examples

#1 Print specific variable

Shows the value of HOME.
$ printenv HOME
Output: /home/user

#2 Print all variables

Lists all environment variables sorted alphabetically.
$ printenv | sort

#3 Check if variable exists

Uses exit code to check if a variable is defined.
$ printenv API_KEY > /dev/null 2>&1 && echo "Set" || echo "Not set"

#4 Print multiple variables

Displays the values of HOME, USER, and SHELL.
$ printenv HOME USER SHELL
Output: /home/user user /bin/bash

#5 Search for variables

Finds all proxy-related environment variables.
$ printenv | grep -i proxy

#6 Use in script

Gets DB_HOST or falls back to localhost if not set.
$ DB_HOST=$(printenv DB_HOST || echo "localhost")

Tips & Best Practices

Check variable existence: printenv VARNAME returns exit code 0 if set, 1 if not. More reliable than testing echo $VAR which shows empty string for unset vars.
printenv vs echo $VAR: printenv VAR shows only exported variables. echo $VAR shows both local and exported. printenv has useful exit codes.
Only environment variables: printenv shows only exported environment variables, not local shell variables. Use set or declare to see all variables.

Frequently Asked Questions

How do I check if an environment variable is set?
Use printenv VARNAME. It returns exit code 0 if set, 1 if not. Or: printenv VARNAME && echo "set" || echo "not set".
What is the difference between printenv and env?
Both show environment variables. printenv can show a single variable easily. env can also run commands with modified environments.
Why does printenv not show my variable?
printenv only shows exported variables. If you set a variable without export, it is a local shell variable and not visible to printenv.

Master Linux with Professional eBooks

Curated IT eBooks covering Linux, DevOps, Cloud, and more

Browse Books →