Run these commands in Bash:
NODE_ENV=production echo $NODE_ENV
outputs ""NODE_ENV=production && echo $NODE_ENV
outputs "production"export NODE_ENV=production && echo $NODE_ENV
outputs "production"
Now there is a file index.js:
console.log(process.env.NODE_ENV)
then run these commands in Bash:
NODE_ENV=production node index.js
outputs "production"NODE_ENV=production && node index.js
outputs "undefined"export NODE_ENV=production && node index.js
outputs "production"
I get confused by these commands, why are the results different?
Edit:
Thanks everyone. Now I give my explanations, maybe it's helpful for other guys.
NODE_ENV=production echo $NODE_ENV
, Bash expends $NODE_ENV
before running this command, at this point $NODE_ENV
is not set so the result is blank.
NODE_ENV=production && echo $NODE_ENV
, these are two commands, the second command command only runs if the first command succeeds. Before running the second command Bash expends $NODE_ENV
which is set at this point.
NODE_ENV=production node index.js
, prefixing a variable definition to a command makes this variable available to this command.
NODE_ENV=production && node index.js
, node is an external commands, Bash forks it and runs it in a sub-process, node doesn't get $NODE_ENV
from parent process.
export NODE_ENV=production && node index.js
, export
makes the variable available to sub-processes, so node gets $NODE_ENV
.