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 set a variable parent
so that it would print C:\a
without changing the current working directory to ..
打印C:\ a \ b,我想设置一个变量父级,以便打印C:\ a而不将当前工作目录更改为..
Is this possible?
这可能吗?
3 个解决方案
#1
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%
#2
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.
编辑:请注意,到目前为止,包括我的所有解决方案,如果当前文件夹是驱动器的根目录,将会出现问题。没有干净简单的方法,因为用户模式确实没有驱动器的父级。
#3
Use
pushd targetFolder
set current=%cd%
popd
Pushd/popd maintain a stack of previously visited directories.
Pushd / popd维护一堆先前访问过的目录。
#1
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%
#2
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.
编辑:请注意,到目前为止,包括我的所有解决方案,如果当前文件夹是驱动器的根目录,将会出现问题。没有干净简单的方法,因为用户模式确实没有驱动器的父级。
#3
Use
pushd targetFolder
set current=%cd%
popd
Pushd/popd maintain a stack of previously visited directories.
Pushd / popd维护一堆先前访问过的目录。