如何在Windows中获取批处理脚本的路径?

时间:2010-09-30 03:46:52

标签: windows batch-file

我知道%0包含批处理脚本的完整路径,例如c:\path\to\my\file\abc.bat

我希望path等于c:\path\to\my\file

我怎么能实现这个目标?

8 个答案:

答案 0 :(得分:478)

%~dp0将成为目录。 Here's some documentation on all of the path modifiers。有趣的东西: - )

要删除最后的反斜杠,可以使用:n,m子串语法,如下所示:

SET mypath=%~dp0
echo %mypath:~0,-1%

不幸的是,我认为没有办法将%0语法与:~n,m语法结合起来。

答案 1 :(得分:15)

%~dp0可能是相对路径。 要将其转换为完整路径,请尝试以下方法:

pushd %~dp0
set script_dir=%CD%
popd

答案 2 :(得分:9)

您可以使用以下脚本来获取路径,而不会尾随“\”

for %%i in ("%~dp0.") do SET "mypath=%%~fi"

答案 3 :(得分:0)

%〜dp0 -返回脚本执行的路径

但是,重要的是也要了解以下内容:

%CD%-在运行时返回当前路径,例如,如果您使用“ cd folder1” 然后进入“ cd folder2”进入其他文件夹,它将返回完整路径,直到folder2,而不是脚本所在的原始路径

答案 4 :(得分:-2)

您可以使用%~dp0,d表示仅驱动器,p表示仅路径,0是批处理文件的完整文件名的参数。

例如,如果文件路径为C:\ Users \ Oliver \ Desktop \ example.bat,则参数等于C:\ Users \ Oliver \ Desktop \,也可以使用命令set cpath=%~dp0 && set cpath=%cpath:~0,-1%并使用%cpath%变量以删除斜杠。

答案 5 :(得分:-4)

%cd%将为您提供脚本运行所在目录的路径。

只需运行:

echo %cd%

答案 6 :(得分:-8)

那将是%CD%变量。

@echo off
echo %CD%

%CD%返回批处理脚本所在的当前目录。

答案 7 :(得分:-8)

我正在使用Windows 7计算机,我最终使用下面的行来获取我的bash脚本的绝对文件夹路径。

在查看http://www.linuxjournal.com/content/bash-parameter-expansion后,我得到了这个解决方案。

#Get the full aboslute filename.
filename=$0
#Remove everything after \. An extra \ seems to be necessary to escape something...
folder="${filename%\\*}"
#Echo...
echo $filename
echo $folder