問題描述
假設我們要在批處理a.bat里調用執行批處理b.bat
,b.bat
需要知道b.bat
的當前位置,并執行run.exe
,如下:
// directory structure// c:// -a.bat// -program// -b.bat// -run.exe// a.batcall "%cd%/program/b.bat"http:// b.bat"%cd%/run.exe" |
那么現在能不能成功執行run.exe
呢?
問題分析
%cd%
和%~dp0
都能用來表示當前目錄,但是他們在不同的使用場景下,功能卻不相同:
%cd%
代表的是當前工作目錄(current working directory,variable); %~dp0
代表的是當前批處理文件所在完整目錄(the batch file's directory,fixed)。我們來看看下面的例子:
// directory structure// c:// -c.bat// -program// -d.bat// c.batcall "%cd%/program/d.bat"http:// d.bat@echo offecho cd = %cd%echo dp0 = %~dp0 |
直接運行d.bat
,結果為
cd = C:/programdp0 = C:/program/ |
直接運行c.bat
,結果為
cd = C:/dp0 = C:/program/ |
從上面的結果可以看出:
d.bat
時,當前工作目錄為d.bat
所在目錄; 執行c.bat
時,當前工作目錄為c.bat
所在目錄,即使在調用d.bat
后,該工作目錄依舊是c.bat
所在目錄。問題解決
讓我們再來看看問題描述中提及的問題——能不能成功執行run.exe
呢?
答案是:不能。“ %cd%/run.exe
”表示的是“ C:/run.exe
”,并非“ C:/program/run.exe
”。那么如何更改呢?
有兩種方案:
// plan A// change the current working directory// a.batcd "%~dp0"call "%cd%/program/b.bat"http:// b.batcd "%~dp0""%cd%/run.exe"http:// plan B// using %~dp0 directly// a.batcall "%~dp0program/b.bat"http:// b.bat"%~dp0run.exe" |
問題延伸
上面的解決方案中plan A通過更改當前目錄來解決該問題,可以這里面也存在另外一個問題,讓我們看下面的例子:
// directory structure// c:// -program// -f.bat// d:// -e.bat// plan A// change the current working directory// e.batcd "%~dp0"call "c:/program/f.bat"http:// f.batcd "%~dp0""%cd%/run.exe" |
現在e.bat
和f.bat
不在同一個盤符了,從e.bat
切換當前工作目錄到f.bat
直接使用cd是不行的,必須要使用:
cd /d "%~dp0" |
這個地方容易疏忽,切記不要犯錯。
問題總結
我們來重申下%~dp0
和%cd%
的區別, %cd%
和
新聞熱點
疑難解答