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

本文翻译自: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%返回批处理脚本所在的当前目录。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值