简体   繁体   English

在Shell脚本OS X中设置环境变量

[英]Setting environment variables in shell script OS X

I'm trying to create a Shell Script to automate my local dev environment. 我正在尝试创建一个Shell脚本来自动化我的本地开发环境。 I need it start some processes (Redis, MongoDB, etc.), set the environment variables then start the local web server. 我需要它启动一些进程(Redis,MongoDB等),设置环境变量,然后启动本地Web服务器。 I'm working on OS X El Capitan. 我正在使用OS X El Capitan。

Everything is working so far, except the environment variables. 到目前为止,一切正常,除了环境变量。 Here is the script: 这是脚本:

#!/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

The .env file is using the format export VARIABLE="value" .env文件使用的格式为export VARIABLE="value"

The environment variables are just not being set at all. 根本没有设置环境变量。 But, if I run the exact command source path-to-file.env before running the script then it works. 但是,如果我在运行脚本之前运行确切的命令source path-to-file.env ,则它可以工作。 I'm wondering why the command would work independently but not inside the shell script. 我想知道为什么该命令可以独立运行,但不能在shell脚本中运行。

Any help would be appreciated. 任何帮助,将不胜感激。

When you execute a script, it executes in a subshell, and its environment settings are lost when the subshell exits. 当您执行脚本时,它会在子shell中执行,并且当该子shell退出时,其环境设置会丢失。 If you want to configure your interactive shell from a script, you must source the script in your interactive shell. 如果你想从脚本配置交互shell,你必须source在你的交互shell脚本。

$ source start-local.sh

Now the environment should appear in your interactive shell. 现在环境应该出现在您的交互式外壳中。 If you want that environment to be inherited by subshells, you must also export any variables that will be required. 如果您希望该环境被子Shell继承,则还必须export所有需要的变量。 So, for instance, in path-to-file.env, you'd want lines like: 因此,例如,在path-to-file.env中,您需要以下行:

export MY_IMPORTANT_PATH_VAR="/example/blah"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM