如何递归扩展环境变量? [英] How to recursively expand an environment variable?
问题描述
假设以下内容:
echo%MY_ENV_VAR%
扩展为%USERPROFILE% \some\path
echo%USERPROFILE%
扩展为 C:\Users UserMyUser
我的目标是在以下路径创建一个空文件: C:\Users\ \MyUser\some\path\FOO.txt
。
My goal is to create an empty file at the following path: C:\Users\MyUser\some\path\FOO.txt
.
我尝试了以下命令: type nul > %MY_ENV_VAR%\FOO.txt
不幸的是,输出是错误,指出系统找不到指定的路径。
Unfortunately the output is an error which states The system cannot find the path specified.
我敢肯定这是因为shell没有递归扩展%MY_ENV_VAR%
试图找到以%USERPROFILE%
开头的文字路径。
I'm pretty certain this is because the shell is not recursively expanding %MY_ENV_VAR%
and it's trying to find a literal path that begins with %USERPROFILE%
.
我怎样才能最好地实现自己的目标?
How can I best accomplish my goal?
推荐答案
rem Create the problem
set "MY_ENV_VAR=%%USERPROFILE%%\some\path"
echo %MY_ENV_VAR%
rem One solution
call set "MY_ENV_VAR=%MY_ENV_VAR%"
echo %MY_ENV_VAR%
在调用
行中,解析器将%MY_ENV_VAR%
替换为变量的内容,生成
In the call
line, the parser will replace %MY_ENV_VAR%
with the content of the variable, generating
call set "MY_ENV_VAR=%USERPROFILE%\some\path"
执行此命令后,调用
将强制执行第二个解析阶段,生成
When this command is executed, the call
will force a second parse phase, generating
set "MY_ENV_VAR=C:\Users\MyUser\some\path"
当然,如果 USERPROFILE
包含另一个变量引用,则必须重复该过程。
Of course, if USERPROFILE
contains another variable reference, the process must be repeated.
已编辑-为递归问题添加了解决方案,并将所有代码置于su中肉丁。
edited - Added a "solution" to the "recursive" problem and placed all the code inside a subroutine.
@echo off
setlocal enableextensions disabledelayedexpansion
rem Create the problem
set "_1first=c:\users"
set "_2second=%%_1first%%\test"
set "_3third=%%_2second%%\so & me\path"
set "_4fourth=%%_3third%%"
set "MY_ENV_VAR=%%_4fourth%%"
echo inner variables
echo -----------------------------
set _
echo -----------------------------
echo(
echo "MY_ENV_VAR = [%MY_ENV_VAR%]"
call :expandInnerVariables MY_ENV_VAR
echo "MY_ENV_VAR = [%MY_ENV_VAR%]"
goto :eof
:expandInnerVariables varName
setlocal enableextensions disabledelayedexpansion
set "aux=="
for /l %%i in (0 1 100) do (
setlocal enabledelayedexpansion
if "!%~1!"=="" (
endlocal & goto :endExpand
) else for /f "delims=" %%a in ("=!%~1!") do (
endlocal & call set "%~1%%a"
setlocal enabledelayedexpansion
for /f "delims=" %%b in ("=!%~1!") do (
endlocal & set "aux=%%b" & if %%a==%%b goto :endExpand
)
)
)
:endExpand
endlocal & set "%~1%aux%"
goto :eof
这篇关于如何递归扩展环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!