Linux command: env

Quick startenvCommands, used to run commands and interact with environment variables

ThisenvCommands can be used to pass environment variables without setting them on the external environment (current shell).

Suppose you want to run a Node.js application and setUSERVariable.

You can run

env USER=flavio node app.js

withUSEREnvironment variables can be accessed from Node.js applications through Nodeprocess.envinterface.

You can also use the following command to run the command to clear all the environment variables that have been set:-iOptions:

env -i node app.js

In this case, you will receive an error message:env: node: No such file or directorybecausenodeThe command cannot be accessed becausePATHThe variable used by the shell to find commands in the public path is not set.

Therefore, you need to pass the full path tonodeprogram:

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

Try simpleapp.jsFiles containing the following content:

console.log(process.env.NAME)
console.log(process.env.PATH)

You will see the output

undefined
undefined

You can pass an env variable:

env -i NAME=flavio node app.js

and the output will be

flavio
undefined

Removing the -i option will make PATH available again inside the program:

The env command can also be used to print out all the environment variables, if ran with no options:

env

it will return a list of the environment variables set, for example:

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

You can also make a variable inaccessible inside the program you run, using the -u option, for example this code removes the HOME variable from the command environment:

env -u HOME node app.js

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

Download my free Linux Commands Handbook


More cli tutorials: