Kantesh
Kantesh

Reputation: 875

how concatenate two variables in batch script?

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

Upvotes: 20

Views: 158543

Answers (3)

user6262603
user6262603

Reputation:

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.

Upvotes: 11

jeb
jeb

Reputation: 82202

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

Upvotes: 5

Sergey Podobry
Sergey Podobry

Reputation: 7189

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%

Upvotes: 27

Related Questions