问题
I have a nodejs javascript project, but I would like to set a bunch of environment variables locally. created a bash file that just exports some variables:
#!/usr/bin/env bash
export waka=flaka
export fat=booty
When I use the dot to source and run the file from the command line it works fine:
. ./env.sh
And I can see the variable has been set
echo $waka # prints "flaka"
But then I try to take this command and make it an npm script by adding it to my package.json
scripts: {
"set-env": ". ./env.sh",
...
}
and then run it:
npm run set-env
The script is run but the environment variables are not saved:
echo $waka # prints undefined (assuming you didn't already run it from command line)
So, I'm wondering why it doesn't save the envrionment variables as an npm script and if it's possible to run the bash script from an npm script in a way such that the environment variables will be saved for the rest of the command prompt session. Thanks!
回答1:
npm
is not a shell command; it runs in a separate process that forks another shell in order to run the command specified by set-env
. env.sh
is executed, but then that shell immediately exits, at which point the changes are gone (and then npm
itself exits).
来源:https://stackoverflow.com/questions/51162609/why-cant-i-set-env-variables-by-running-a-bash-script-from-an-npm-script