Why Can't I Set Env Variables By Running A BASH Script From An Npm Script?

[亡魂溺海] 提交于 2019-12-10 22:40:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!