In the following two (simplified examples) batch files I am having difficulty when I want to overwrite some variables:
@echo off
set var=D:
set var_2=%var%\DOMAIN
set var_3=%var_2%\sub_domain
call batch_test2.bat
@echo %var%
@echo %var_2%
@echo %var_3%
@echo off
if 1==1 (
set var=E:
set var_2=%var%\Component
set var_3=%var_2%\comp1
)
E:
D:\Component
D:\DOMAIN\comp1
E:
E:\Component
E:\DOMAIN\comp1
How can I get the expected_output using multiple variables?
This is, again, the infamous early variable expansion problem: batch scripts substitute variables early, before a block starts.
that means %var_2% will be fixed to the first value. to get around that, use setlocal enabledelayedexpansion
and then surround the variable with "!" instead of "%".
For batch_test 2 you should use delayed expansion and tunneling:
@echo off
setlocal enableDelayedExpansion
if 1==1 (
set var=E:
set var_2=!var!\Component
set var_3=!var_2!\comp1
)
endlocal & (
set var=%var%
set var_2=%var_2%
set var_3=%var_3%
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With