Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EnableDelayedExpansion and still set global environment variables

Tags:

batch-file

setlocal
for /F "tokens=1,2" %%a in (%env_cells%) do (
    call :env_setter env_setter_%%a
)
goto:EOF

:env_setter
rem doesn't do anything
endlocal
call %%1
goto:eof

The problem is the above disables the setting of global variables in all calls spawned by :env_call. Is there a way to resolve this?

Perhaps this is a more detailed explanation:

env_setter is a call to a batch file that itself contains set calls with the intention to set environment variables on this calling context. Because setlocal is enabled during the call to !env_cell! and the endlocal in :env_cell does not appear to disable endlocal, said set calls do not change this context as intended.

In this particular example, one can use %%a but I wish to understand this functionality in general.

Is there a manual way to access a variable value reflectively in a if/for block?

like image 608
MetaChrome Avatar asked Oct 28 '25 03:10

MetaChrome


2 Answers

Throw your variables over the wall!

@echo off &setlocal
echo(

echo this obviously doesn't work
set "Counter="
for /l %%a in (1 1 5) do (
    SETLOCAL ENABLEDELAYEDEXPANSION
    set "Counter=!Counter!1"
    set "Variable=!Variable!!Counter!"
    echo !Counter!:!Variable!
    endlocal
)
echo Counter's value in the calling environment : %Counter%
echo Variable's value in the calling environment: %Variable%
echo(
    
echo throw your variables over the wall!
set "Counter="
for /l %%a in (1 1 5) do (
    SETLOCAL ENABLEDELAYEDEXPANSION
    set "Counter=!Counter!1"
    set "Variable=!Variable!!Counter!"
    echo !Counter!:!Variable!
    for /f %%a in ('set Counter^&set Variable') do (if "!"=="" endlocal)&set "%%a"
)
echo Counter's value in the calling environment : %Counter%
echo Variable's value in the calling environment: %Variable%
            
like image 175
Endoro Avatar answered Oct 30 '25 04:10

Endoro


It's not possible to use an endlocal in a function to leave a setlocal which is set outside the function.

But when a syntax error occours all setlocal instances are still alive and can't be removed with endlocal, so this can set global variables.

setlocal
for /F "tokens=1,2" %%a in (%env_cells%) do (
    call :env_setter env_setter_%%a
)
goto:EOF

:env_setter
set myNewGlobal=1
call :haltAndStore
goto:eof

:haltAndStore
()
like image 20
jeb Avatar answered Oct 30 '25 05:10

jeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!