在cmd.exe的,你怎么能得到一个变量逃脱SETLOCAL命令? [英] In cmd.exe, how can you get one variable to escape the setlocal command?
问题描述
我经常发现自己使用 SETLOCAL
在的cmd.exe
来避免污染环境变量空间与临时变量(并确保这两个命令扩展和延迟扩展是有效)。
I frequently find myself using setlocal
within cmd.exe
to avoid polluting the environment variable space with temporary variables (and to ensure both command extensions and delayed expansion are active).
不过,我就如何做到这一点如果我真的希望这些变量之一的损失提供给
However, I'm at a loss on how to do this if I actually want one of those variables to be made available.
考虑以下code,让你的当前目录的最后一个组件(这样 C:\\ PAX \\ DIR1
会给你方向1
)
Consider the following code which gives you the final component of the current directory (so c:\pax\dir1
would give you dir1
):
@echo off
:main
setlocal enableextensions enabledelayedexpansion
call :func
echo.main_folder = %folder%
endlocal
goto :eof
:func
setlocal enableextensions enabledelayedexpansion
set temp=%cd%
set folder=
:funcloop1
if not "x%temp:~-1%"=="x\" (
set folder=!temp:~-1!!folder!
set temp=!temp:~1,-1!
goto :funcloop1
)
echo.func_folder = %folder%
endlocal
goto :eof
当我运行它,我得到的输出:
When I run this, I get the output:
func_folder = dir1
main_folder =
,你可以看到%文件夹%
变量不下去了 ENDLOCAL
。但是,如果我离开关 SETLOCAL / ENDLOCAL
从功能,温度
varaible污染<$ C的命名空间$ C>主。
and you can see that the %folder%
variable does not survive the endlocal
. However, if I leave off the setlocal/endlocal
from the function, the temp
varaible pollutes the namespace of main
.
我知道我可以只使用 SET TEMP =
在年底FUNC
,这将消除环境变量但是,这并不涵盖我已经使用在范围之外的变量(它得到在这种情况下完全破坏)的情况。
I know I can just use set temp=
at the end of func
and this will remove the environment variable but that doesn't cover the case where I'm already using that variable in the outside scope (it gets totally destroyed in that case).
是否有的cmd.exe
办法让环境变量的选择组传播到外界的范围,同时仍$ P $从影响它pventing别人呢?换句话说,你可以有局部变量和返回变量?
Is there a way in cmd.exe
to allow a select group of environment variables to propogate to the outside scope while still preventing others from affecting it? In other words, can you have both local variables and return variables?
除此之外,请不要告诉我有得到最终的路径组件的更好的方法。这仅是一个示例情况
Aside, please don't tell me there's a better way of getting the final path component. That is an example case only.
其实,你的可以的告诉我一个更好的办法,因为它会是不错的知道,但它不会回答我的具体问题: - )
Actually, you can tell me a better way since it'd be nice to know but it won't be answering my specific question :-)
推荐答案
解决这个问题的解决方案是利用一个事实,即CMD壳评估一行接一行的基础变量 - 所以把ENDLOCAL同行SET语句(S)给出了我们想要的结果:来源: ss64.com
"The solution to this is to take advantage of the fact that the CMD shell evaluates variables on a line-by-line basis - so placing ENDLOCAL on the same line as the SET statement(s) gives the result we want:" source: ss64.com
因此改变FUNC的ENDLOCAL:这个...
So changing the endlocal of func: to this...
endlocal & set folder=%folder%
...会得到你想要的行为。
...will get you the behaviour you want.
这篇关于在cmd.exe的,你怎么能得到一个变量逃脱SETLOCAL命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!