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: