2017-09-11 40 views
1

我的工作在多個批處理文件,我想他們分享一些變量,所以我創建了一個擁有所有這些設置SetupEnv一個批處理文件:常見的批處理文件來設置變量

rem General setup 
:: To pause or not after running a batch file 
SET isPause = true 

:: The directory where your source code is located 
SET directory = D 

:: The folders where your primary & secondary source code is located 
:: I like to have two source code folders, if you don't then just have them pointing to the same folder 
SET primary_source_code = \Dev\App 
SET secondary_source_code = \Dev\App2 

:::::::::::::::::::::::::::::::::::::::::::: XAMPP ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: 
rem If you're using XAMPP then set these up 
:: Your destination folder 
SET base_destination = C:\xampp\htdocs 

:: The base url that is pointing to your destination folder (in most cases it's localhost) 
SET base_url = http://10.0.2.65 

:::::::::::::::::::::::::::::::::::::::::: Angular ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: 
rem If you're using angular set these up 
:: The folder where you built code is copied 
SET build_file = dist 

而且從另一個批處理文件我先調用該文件:

::setup 
call ../SetupEnv 

echo %directory% dir 
pause; 

的問題是,即使該文件運行順利,我可以在東西被安裝,該變量不能跨來我」的文件輸出看到米從它呼叫。因此在該例中%directory%未被打印。

編輯 我使用Joey's answer也試過:

::setup 
for /f "delims=" %%x in (../SetupEnv.txt) do (set "%%x") 

echo %directory% dir 
pause 

但是,這並沒有工作,要麼和%directory%沒有得到印刷

+0

'call'創建一個子shell,所以你在那裏設置變量,而不是父級。 – Gene

+0

@Gene如果我沒有使用通話,但它在運行該批處理文件後關閉 –

+0

@ Gene:無關緊要,只要不涉及'setlocal' /'endlocal'。 Naguib:用'set'命令刪除'='周圍的空格。它們分別成爲變量名稱的一部分。 – Stephan

回答

1

設置變量在call版作品的批處理文件,只要因爲在調用的批處理文件中不使用setlocal(當它返回時,會有一個暗示endlocal,所以變量將丟失):

> type a.bat 
set var=old 
echo %var% 
call b.bat 
echo %var% 

> type b.bat 
set var=new 

> a.bat 

> set var=old 

> echo old 
old 

> call b.bat 

> set var=new 

> echo new 
new 

> 

的替代for解決方案,我會稍微改變爲:

for /f "delims=" %%a in ('type b.bat^|findstr /bic:"set "') do %%a 

這僅將「執行」線,與set(忽略大小寫)開始,這樣可以保持內部的任何意見文件。

注意:... do set "%%a"將另一個set添加到行(您已經在文件中有一個),導致set "set var=value",您顯然不想要。

相關問題