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

3 Answers 3

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%
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you!!! it worked!! For disabling just to do is "setlocal DisableDelayedExpansion"?
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 stackoverflow.com/questions/3262287/…
You may review a more detailed description of this matter in this question
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.

2 Comments

This is much more interesting than the vanilla setlocal enabledelayedexpansion. It also works with global variables.
can you explain why we need to call call before set in the fourth line but not in the first three?
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

2 Comments

It doesn't echo the value "hi" instead it echos AB
You are right, I didn't read the last sentence, I only see the question about concatenating

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.