2016-08-19 145 views
0

我正在嘗試創建一個Shell腳本來自動執行我的本地開發環境。我需要它啓動一些進程(Redis,MongoDB等),設置環境變量,然後啓動本地Web服務器。我正在開發OS X El Capitan。在shell腳本中設置環境變量OS X

到目前爲止,除了環境變量之外,一切都工作正常。下面是該腳本:

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

該文件究竟是什麼? echo $ -'如何在您的交互式shell和它所在的腳本之間進行比較? –

+0

......最有可能的情況是你在'〜/ .bashrc'或類似文件中運行'set -a'。 –

+0

(假設有合理的期望 - 即,您不希望腳本退出後變量交互式可用)。 –

回答

2

當您執行腳本時,它將在子shell中執行,並且在子shell退出時其環境設置將丟失。如果要從腳本配置交互式shell,則必須在交互式shell中使用source腳本。

$ source start-local.sh 

現在環境應該出現在交互式shell中。如果你希望這個環境被子殼體繼承,你還必須使用任何將需要的變量。因此,例如,在path-to-file.env中,您需要如下行:

export MY_IMPORTANT_PATH_VAR="/example/blah" 
+0

OP *是*源文件。我*推測*他們正在檢查變量是否通過之後調用的'pm2'服務的行爲來設置;如果他們打算讓它們在外殼中可用,那麼是的,這是一個明顯的期望失敗。 –

+0

我在shell中使用'echo $ -'來檢查並且它們沒有被設置。這確實是有道理的。有沒有辦法做到我想要做的事情,而不是單獨採購每個文件? – nickcorin

+1

我在*腳本中看到'source' invocations *。沒有跡象表明腳本本身來自交互式shell。 –

相關問題