Linux命令:env

快速入门env命令,用于运行命令并与环境变量交互

env命令可用于传递环境变量,而无需在外部环境(当前外壳)上设置它们。

假设您要运行Node.js应用并设置USER可变的。

你可以跑

env USER=flavio node app.js

USER可通过Node从Node.js应用访问环境变量process.env界面。

您也可以使用以下命令来运行命令,以清除所有已设置的环境变量:-i选项:

env -i node app.js

在这种情况下,您会收到一条错误消息:env: node: No such file or directory因为node该命令无法访问,因为PATHshell用于在公用路径中查找命令的变量未设置。

因此,您需要将完整路径传递给node程序:

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

尝试简单app.js包含以下内容的文件:

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

您将看到输出

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: