windows 如何在Windows上将变量设置为父目录的路径?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/975521/
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
How to SET a variable to the path of parent directory on windows?
提问by Peter Perhá?
Struggling with command line again, I have figure out that I can store the current working directory in a variable like so:
再次与命令行苦苦挣扎,我发现我可以将当前工作目录存储在一个变量中,如下所示:
SET current=%cd%
How would I set parent though? SET parent=%..%
does not work, as it echoes %..%
我将如何设置父级?SET parent=%..%
不起作用,因为它回响%..%
Basically, calling a batch script C:\a\b\myscript.bat
with the following contents:
基本上,调用C:\a\b\myscript.bat
具有以下内容的批处理脚本:
@echo off
set current=%cd%
echo %current%
prints C:\a\b
and I should like to seta variable parent
so that it would print C:\a
without changing the current working directory to ..
打印C:\a\b
,我想设置一个变量,parent
以便在C:\a
不将当前工作目录更改为..
Is this possible?
这可能吗?
回答by Binary Worrier
Move up a directory, remembering the current, set the parent, and then pop down a directory, back to where you started
上移一个目录,记住当前,设置父目录,然后下一个目录,回到你开始的地方
@echo off
set current=%cd%
pushd ..
set parent=%cd%
popd
echo current %current%
echo parent %parent%
回答by RBerteig
You could also do something like this:
你也可以做这样的事情:
set current=%CD% set parent=%CD%\..
It doesn't give you the canonical name of the parent, but it should always be a valid path to the parent folder. It will also be somewhat faster than the solutions involving pushd and popd, but that won't be the primary consideration in a batch file.
它不会为您提供父文件夹的规范名称,但它应该始终是父文件夹的有效路径。它也将比涉及 pushd 和 popd 的解决方案快一些,但这不是批处理文件中的主要考虑因素。
Edit:Note that all of the solutions so far, including mine here, will have problems if the current folder is the root of a drive. There is no clean and easy way out of that one, since there really is no parent of a drive visible to user mode.
编辑:请注意,如果当前文件夹是驱动器的根目录,则到目前为止的所有解决方案,包括我的解决方案,都会出现问题。没有什么干净和简单的方法可以解决这个问题,因为对于用户模式确实没有可见的驱动器的父级。
回答by Richard
Use
用
pushd targetFolder
set current=%cd%
popd
Pushd/popd maintain a stack of previously visited directories.
Pushd/popd 维护一堆以前访问过的目录。