20

I want to do something like this in batch script. Please let me know if this is the proper or possible way to do it or any other way?

set var1=A

set var2=B

set AB=hi

set newvar=%var1%%var2%

echo %newvar%  

This should produce the value "hi".

Kantesh
  • 875
  • 3
  • 8
  • 19

3 Answers3

27

Enabling delayed variable expansion solves you problem, the script produces "hi":

setlocal EnableDelayedExpansion

set var1=A
set var2=B

set AB=hi

set newvar=!%var1%%var2%!

echo %newvar%
Sergey Podobry
  • 7,101
  • 1
  • 41
  • 51
  • 2
    Thank you!!! it worked!! For disabling just to do is "setlocal DisableDelayedExpansion"? – Kantesh Oct 21 '11 at 08:48
  • 1
    No, you need to call endlocal. But beware that all variables in setlocal-endlocal block are local and not available from outside. You can save needed variables as described in http://stackoverflow.com/questions/3262287/make-an-environment-variable-survive-endlocal – Sergey Podobry Oct 21 '11 at 10:12
  • You may review a more detailed description of this matter in [this question](http://stackoverflow.com/questions/7882395/why-is-delayed-expansion-in-a-batch-file-not-working-in-this-case) – Aacini Oct 27 '11 at 01:45
11

You can do it without setlocal, because of the setlocal command the variable won't survive an endlocal because it was created in setlocal. In this way the variable will be defined the right way.

To do that use this code:

set var1=A

set var2=B

set AB=hi

call set newvar=%%%var1%%var2%%%

echo %newvar% 

Note: You MUST use call before you set the variable or it won't work.

5

The way is correct, but can be improved a bit with the extended set-syntax.

set "var=xyz"

Sets the var to the content until the last quotation mark, this ensures that no "hidden" spaces are appended.

Your code would look like

set "var1=A"
set "var2=B"
set "AB=hi"
set "newvar=%var1%%var2%"
echo %newvar% is the concat of var1 and var2
echo !%newvar%! is the indirect content of newvar
jeb
  • 78,592
  • 17
  • 171
  • 225