The env command is a versatile tool used in Linux, macOS, WSL, and UNIX environments to run commands while manipulating and interacting with environment variables.

Passing Environment Variables

One of the main use cases for the env command is to pass environment variables to a command, without permanently setting them in the current shell. For example, if you want to run a Node.js app and set the USER variable to it, you can use the env command as follows:

env USER=flavio node app.js

By doing this, the USER environment variable will be accessible from the Node.js app through the process.env interface.

Clearing Environment Variables

If you wish to clear all the environment variables already set before running a command, the -i option can be used. However, it’s important to note that you will need to provide the full path to the command you want to run. For example:

env -i /usr/local/bin/node app.js

In the above example, we are running the node command with the app.js file, but since all environment variables are cleared, the PATH variable is not available, leading to an error. To resolve this, we provide the full path to the node program.

Printing Environment Variables

The env command can also be used to print out all the environment variables. Running env with no options will display a list of the environment variables that are set. For example:

env

The output will show a list of environment variables, including HOME, LOGNAME, PATH, SHELL, etc.

Making Variables Inaccessible

Using the -u option in combination with the env command allows you to make specific variables inaccessible within the program you run. For instance, running the following command will remove the HOME variable from the command environment:

env -u HOME node app.js

This can be useful when you want to restrict access to certain variables within a program.

The env command is a valuable tool for managing environment variables and controlling how they interact with your commands. Whether you need to pass variables, clear the environment, print variables, or make them inaccessible, the env command provides a flexible solution.