为什么不能通过Npm脚本运行BASH脚本来设置Env变量? [英] Why Can't I Set Env Variables By Running A BASH Script From An Npm Script?
问题描述
我有一个nodejs javascript项目,但我想在本地设置一堆环境变量.创建了一个仅导出一些变量的bash文件:
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
我可以看到变量已设置
echo $waka # prints "flaka"
但是我尝试通过将此命令添加到我的package.json中,使其成为npm脚本
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",
...
}
然后运行它:
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)
所以,我想知道为什么它不将环境变量保存为npm脚本,以及是否有可能以某种方式从npm脚本运行bash脚本,以便将环境变量保存为其余部分.命令提示符会话.谢谢!
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!
推荐答案
npm
不是shell命令;它在一个单独的进程中运行,该进程派生另一个外壳,以运行 set-env
指定的命令. env.sh
被执行,但该外壳程序立即退出,此时更改已消失(然后 npm
本身退出).
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).
这篇关于为什么不能通过Npm脚本运行BASH脚本来设置Env变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!