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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3827567/
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 07:38:32  来源:igfitidea点击:

How to get the path of the batch script in Windows?

windowsbatch-file

提问by Misha Moroshko

I know that %0contains the full path of the batch script, e.g. c:\path\to\my\file\abc.bat

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

I would pathto be equal to c:\path\to\my\file

我会path等于c:\path\to\my\file

How could I achieve that ?

我怎么能做到这一点?

回答by Dean Harding

%~dp0will be the directory. Here's some documentation on all of the path modifiers. Fun stuff :-)

%~dp0将是目录。这是有关所有路径修饰符的一些文档。好玩的东西 :-)

To remove the final backslash, you can use the :n,msubstring syntax, like so:

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

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

I don't believe there's a way to combine the %0syntax with the :~n,msyntax, unfortunately.

不幸的是,我不相信有一种方法可以将%0语法与:~n,m语法结合起来。

回答by duan

You can use following script to get the path without trailing "\"

您可以使用以下脚本获取不带尾随“\”的路径

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

回答by Arnaud

%~dp0may be a relative path. To convert it to a full path, try something like this:

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

pushd %~dp0
set script_dir=%CD%
popd

回答by Hayz

You can use %~dp0, d means the drive only, p means the path only, 0 is the argument for the full filename of the batch file.

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

For example if the file path was C:\Users\Oliver\Desktop\example.bat then the argument would equal C:\Users\Oliver\Desktop\, also you can use the command set cpath=%~dp0 && set cpath=%cpath:~0,-1%and use the %cpath%variable to remove the trailing slash.

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

回答by Uddalak Biswas

%cd%will give you the path of the directory from where the script is running.

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

Just run:

赶紧跑:

echo %cd%

回答by Ruel

That would be the %CD%variable.

那将是%CD%变量。

@echo off
echo %CD%

%CD%returns the current directory the batch script is in.

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

回答by Jonas

I am working on a Windows 7 machine and I have ended up using the lines below to get the absolute folder path for my bash script.

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

I got to this solution after looking at http://www.linuxjournal.com/content/bash-parameter-expansion.

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

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