DOS批處理中%cd%與%~dp0的區別詳解

來源:互聯網
上載者:User
Windows下批處理中%cd%和%~dp0都能用來表示目前的目錄,但是他們在不同的使用情境下,功能卻不相同。下面這篇文章就來給大家詳細介紹了DOS批處理中%cd%與%~dp0的區別,需要的朋友可以參考借鑒。

問題描述

假設我們要在批處理a.bat裡調用執行批處理b.batb.bat需要知道b.bat的當前位置,並執行run.exe,如下:

// directory structure// c:// -a.bat// -program//  -b.bat//  -run.exe// a.batcall "%cd%\program\b.bat"// 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"// d.bat@echo offecho cd = %cd%echo dp0 = %~dp0

直接運行d.bat,結果為

cd = C:\programdp0 = C:\program\

直接運行c.bat,結果為

cd = C:\dp0 = C:\program\

從上面的結果可以看出:

  1. 執行d.bat時,當前工作目錄為d.bat所在目錄;

  2. 執行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"// b.batcd "%~dp0""%cd%\run.exe"// plan B// using %~dp0 directly// a.batcall "%~dp0program\b.bat"// 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"// f.batcd "%~dp0""%cd%\run.exe"

現在e.batf.bat不在同一個盤符了,從e.bat切換當前工作目錄到f.bat直接使用cd是不行的,必須要使用:

cd /d "%~dp0"

這個地方容易疏忽,切記不要犯錯。

問題總結

我們來重申下%~dp0%cd%的區別, %cd%%~dp0都能用來表示目前的目錄,但是他們在不同的使用情境下,功能卻不相同:

  • %cd%代表的是當前工作目錄(current working directory,variable);

  • %~dp0代表的是當前批次檔所在完整目錄(the batch file's directory,fixed)。

從目前我們的使用方式來看,盡量使用%~dp0,不建議使用%cd%,有其他需求除外。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.