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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:28:04  来源:igfitidea点击:

How to SET a variable to the path of parent directory on windows?

windowscommand-linebatch-file

提问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.batwith the following contents:

基本上,调用C:\a\b\myscript.bat具有以下内容的批处理脚本:

@echo off
set current=%cd%
echo %current%

prints C:\a\band I should like to seta variable parentso that it would print C:\awithout 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 维护一堆以前访问过的目录。