Nicholas Corin
Nicholas Corin

Reputation: 2404

Setting environment variables in shell script OS X

I'm trying to create a Shell Script to automate my local dev environment. I need it start some processes (Redis, MongoDB, etc.), set the environment variables then start the local web server. I'm working on 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"

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. I'm wondering why the command would work independently but not inside the shell script.

Any help would be appreciated.

Upvotes: 7

Views: 13599

Answers (1)

Juan Tomas
Juan Tomas

Reputation: 5183

When you execute a script, it executes in a subshell, and its environment settings are lost when the subshell exits. If you want to configure your interactive shell from a script, you must source the script in your interactive 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. So, for instance, in path-to-file.env, you'd want lines like:

export MY_IMPORTANT_PATH_VAR="/example/blah"

Upvotes: 20

Related Questions