我正在尝试创建一个Shell脚本来自动化我的本地开发环境。我需要它启动一些进程(Redis,MongoDB等),设置环境变量然后启动本地Web服务器。我正在研究OS X El Capitan。
到目前为止,除了环境变量之外,一切都在运行。这是脚本:
#!/bin/bash
# Starting the Redis Server
if pgrep "redis-server" > /dev/null
then
printf "Redis is already running.\n"
else
brew services start redis
fi
# Starting the Mongo Service
if pgrep "mongod" > /dev/null
then
printf "MongoDB is already running.\n"
else
brew services start mongodb
fi
# Starting the API Server
printf "\nStarting API Server...\n"
source path-to-file.env
pm2 start path-to-server.js --name="api" --watch --silent
# Starting the Auth Server
printf "\nStarting Auth Server...\n"
source path-to-file.env
pm2 start path-to-server.js --name="auth" --watch --silent
# Starting the Client Server
printf "\nStarting Local Client...\n"
source path-to-file.env
pm2 start path-to-server.js --name="client" --watch --silent
.env
文件使用的格式为export VARIABLE="value"
根本没有设置环境变量。但是,如果我在运行脚本之前运行确切的命令source path-to-file.env
,那么它可以工作。我想知道为什么命令会独立工作但不在shell脚本中。
任何帮助都将不胜感激。
答案 0 :(得分:2)
执行脚本时,它会在子shell中执行,并且当子shell退出时,其环境设置将丢失。如果要从脚本配置交互式shell,则必须source
交互式shell中的脚本。
$ source start-local.sh
现在环境应该出现在交互式shell中。如果您希望子环境继承该环境,则还必须export
任何需要的变量。因此,例如,在path-to-file.env中,您需要以下行:
export MY_IMPORTANT_PATH_VAR="/example/blah"