Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to overwrite an existing variable using another variable in batch files?

Tags:

batch-file

In the following two (simplified examples) batch files I am having difficulty when I want to overwrite some variables:

batch_test 1:

 @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%

batch_test 2:

  @echo off
  if 1==1 (
      set var=E:
      set var_2=%var%\Component
      set var_3=%var_2%\comp1
  )

output:

E:
D:\Component
D:\DOMAIN\comp1

expected_output:

E:
E:\Component
E:\DOMAIN\comp1

How can I get the expected_output using multiple variables?

like image 852
Bobby88 Avatar asked Oct 11 '25 21:10

Bobby88


2 Answers

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 "%".

like image 149
ths Avatar answered Oct 16 '25 06:10

ths


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%
  )
like image 27
npocmaka Avatar answered Oct 16 '25 06:10

npocmaka



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!