本文翻译自:How to get the path of the batch script in Windows?
I know that %0
contains the full path of the batch script, eg c:\\path\\to\\my\\file\\abc.bat
我知道%0
包含批处理脚本的完整路径,例如c:\\path\\to\\my\\file\\abc.bat
I would path
to be equal to c:\\path\\to\\my\\file
我将path
等于c:\\path\\to\\my\\file
How could I achieve that ? 我怎么能实现这一目标?
#1楼
参考:https://stackoom.com/question/g3IX/如何在Windows中获取批处理脚本的路径
#2楼
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=$0
#Remove everything after \. An extra \ seems to be necessary to escape something...
folder="${filename%\\*}"
#Echo...
echo $filename
echo $folder
#3楼
%~dp0
may be a relative path. %~dp0
可以是相对路径。 To convert it to a full path, try something like this: 要将其转换为完整路径,请尝试以下方法:
pushd %~dp0
set script_dir=%CD%
popd
#4楼
您可以使用以下脚本来获取路径而不尾随“\\”
for %%i in ("%~dp0.") do SET "mypath=%%~fi"
#5楼
%~dp0
will be the directory. %~dp0
将是目录。 Here's some documentation on all of the path modifiers . 这里有一些关于所有路径修饰符的文档 。 Fun stuff :-) 好玩的东西 :-)
To remove the final backslash, you can use the :n,m
substring syntax, like so: 要删除最后的反斜杠,可以使用:n,m
substring语法,如下所示:
SET mypath=%~dp0
echo %mypath:~0,-1%
I don't believe there's a way to combine the %0
syntax with the :~n,m
syntax, unfortunately. 我不相信有一种方法可以将%0
语法与:~n,m
语法结合起来。
#6楼
That would be the %CD%
variable. 这将是%CD%
变量。
@echo off
echo %CD%
%CD%
returns the current directory the batch script is in. %CD%
返回批处理脚本所在的当前目录。