windows "%~dp0" 和 ".\" 的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15890856/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 10:25:04  来源:igfitidea点击:

Difference between "%~dp0" and ".\"?

windowsbatch-filecmd

提问by user2259606

Let's say I'm using a batch file and want it to direct to a folder located in the same directory of the batch. If I'm not wrong you would write "%~dp0\whateverfoldername". But can't the same done by just writing ".\whateverfoldername"? If so, what is the difference and/or advantage of the respective command?

假设我正在使用批处理文件并希望它指向位于批处理同一目录中的文件夹。如果我没记错,你会写“%~dp0\whateverfoldername”。但是不能只写“.\whateverfoldername”来做同样的事情吗?如果是这样,相应命令的区别和/或优势是什么?

回答by RGuggisberg

pushd %~dp0

is often used to change to the original directory from which the batch was started. This is very useful in newer OS's when the user may 'Run as administrator' which changes the current directory for you! Try it sometime. Just make a simple bat

常用于切换到批处理开始的原始目录。当用户可以“以管理员身份运行”为您更改当前目录时,这在较新的操作系统中非常有用!有时间试试。做一个简单的蝙蝠

@echo off
echo.CD=%CD%
pushd %~dp0
echo.CD=%CD%
pause

Now run it. Now run it again 'As Administrator' on Vista, Win 7, Win 8, 2008 Server, or 2012 Server. See what happens?

现在运行它。现在在 Vista、Win 7、Win 8、2008 Server 或 2012 Server 上再次“以管理员身份”运行它。走着瞧吧?

回答by Magoo

".\will locate with respect to the CURRENTdirectory, hence if you have changed directories with a CDcommand then you will be looking at THATdirectory, not the directory in which the batch resides.

".\将相对于CURRENT目录定位,因此如果您使用CD命令更改了目录,那么您将查看THAT目录,而不是批处理所在的目录。

In fact, it's normal to create a separate directory, often called \batchor perhaps \belfryto keep batch files. Provided the ,batin question is locared on the path, it will be located. %dp0will yield the location of the .bat.

事实上,创建一个单独的目录是很正常的,通常称为\batch或可能\belfry保存批处理文件。如果有,bat问题的 位于 上path,它将被定位。%dp0将产生 的位置.bat