env
Command in Linux: Understanding and Utilizing Environment Variables
Summary
The env
command in Linux is a simple yet powerful utility for displaying, modifying, and running commands within a specific environment. It allows you to view your current environment variables, set new ones, or execute a program with a modified set of variables.
Introduction
The env
command is primarily used to print the current environment or to run a program in a modified environment, without affecting the parent shell's environment. Environment variables are a set of dynamic named values that can affect the way running processes will behave on a computer. They are used to configure various aspects of system behavior, such as the search path for executables, the location of temporary files, or the preferred language for displaying messages.
Use case and Examples
Displaying the current environment
This command will print a list of all current environment variables and their values to standard output. Each variable and its value will be displayed on a separate line.Running a command with a specific environment variable
This command executescommand_to_run
with the environment variable MY_VARIABLE
set to "my_value". The parent shell's environment remains unchanged. Setting multiple environment variables
This runscommand_to_run
after setting VAR1 to value1 and VAR2 to value2. Ignoring the current environment
The-i
flag tells env
to start with an empty environment, meaning it won't inherit any variables from the current shell. This is useful for isolating the execution of a command. Unsetting an environment variable
The-u
flag allows you to remove (unset) an environment variable before running the command. In this example, VAR_TO_UNSET will be removed from the environment before running command_to_run
. Commonly used flags
Flag | Description | Example |
---|---|---|
-i , --ignore-environment | Start with an empty environment. | env -i command_to_run |
-u , --unset=NAME | Remove the variable NAME from the environment. | env -u MY_VARIABLE command_to_run |
-0 , --null | End each output line with NUL, not newline. Useful for handling filenames with spaces. | env -0 | xargs -0 -n 1 |
--help | Display help information and exit. | env --help |
--version | Output version information and exit. | env --version |