how concatenate two variables in batch script?

前端 未结 3 1338
野的像风
野的像风 2021-02-02 15:54

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         


        
相关标签:
3条回答
  • 2021-02-02 16:26

    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.

    0 讨论(0)
  • 2021-02-02 16:34

    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
    
    0 讨论(0)
  • 2021-02-02 16:37

    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%
    
    0 讨论(0)
提交回复
热议问题