[b]问题描述
[/b]
假设我们要在批处理a.bat里调用执行批处理[code]b.bat[/code],[code]b.bat[/code]需要知道[code]b.bat[/code]的当前位置,并执行[code]run.exe[/code],如下:
// directory structure
// c:
// -a.bat
// -program
// -b.bat
// -run.exe
// a.bat
call "%cd%\program\b.bat"
// b.bat
"%cd%\run.exe"
那么现在能不能成功执行[code]run.exe[/code]呢?
[b]问题分析
[/b]
[code]%cd%[/code]和[code]%~dp0[/code]都能用来表示当前目录,但是他们在不同的使用场景下,功能却不相同:
[list]
[*][code]%cd%[/code]代表的是当前工作目录(current working directory,variable);[/*]
[*][code]%~dp0[/code]代表的是当前批处理文件所在完整目录(the batch file's directory,fixed)。
[/*]
[/list]
我们来看看下面的例子:
// directory structure
// c:
// -c.bat
// -program
// -d.bat
// c.bat
call "%cd%\program\d.bat"
// d.bat
@echo off
echo cd = %cd%
echo dp0 = %~dp0
直接运行[code]d.bat[/code],结果为
cd = C:\program
dp0 = C:\program\
直接运行[code]c.bat[/code],结果为
cd = C:\
dp0 = C:\program\
从上面的结果可以看出:
[list=1]
[*]执行[code]d.bat[/code]时,当前工作目录为[code]d.bat[/code]所在目录;[/*]
[*]执行[code]c.bat[/code]时,当前工作目录为[code]c.bat[/code]所在目录,即使在调用[code]d.bat[/code]后,该工作目录依旧是[code]c.bat[/code]所在目录。[/*]
[/list]
[b]问题解决[/b]
让我们再来看看问题描述中提及的问题——能不能成功执行[code]run.exe[/code]呢?
答案是:不能。“ [code]%cd%\run.exe[/code] ”表示的是“ [code]C:\run.exe[/code] ”,并非“ [code]C:\program\run.exe[/code] ”。那么如何更改呢?
有两种方案:
// plan A
// change the current working directory
// a.bat
cd "%~dp0"
call "%cd%\program\b.bat"
// b.bat
cd "%~dp0"
"%cd%\run.exe"
// plan B
// using %~dp0 directly
// a.bat
call "%~dp0program\b.bat"
// b.bat
"%~dp0run.exe"
[b]问题延伸[/b]
上面的解决方案中plan A通过更改当前目录来解决该问题,可以这里面也存在另外一个问题,让我们看下面的例子:
// directory structure
// c:
// -program
// -f.bat
// d:
// -e.bat
// plan A
// change the current working directory
// e.bat
cd "%~dp0"
call "c:\program\f.bat"
// f.bat
cd "%~dp0"
"%cd%\run.exe"
现在[code]e.bat[/code]和[code]f.bat[/code]不在同一个盘符了,从[code]e.bat[/code]切换当前工作目录到[code]f.bat[/code]直接使用cd是不行的,必须要使用:
这个地方容易疏忽,切记不要犯错。
[b]问题总结[/b]
我们来重申下[code]%~dp0[/code]和[code]%cd%[/code]的区别,[code] %cd%[/code]和[code]%~dp0[/code]都能用来表示当前目录,但是他们在不同的使用场景下,功能却不相同:
[list]
[*][code]%cd%[/code]代表的是当前工作目录(current working directory,variable);[/*]
[*][code]%~dp0[/code]代表的是当前批处理文件所在完整目录(the batch file's directory,fixed)。[/*]
[/list]
从目前我们的使用情况来看,尽量使用[code]%~dp0[/code],不建议使用[code]%cd%[/code],有其他需求除外。
[b]总结[/b]
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。