Windows 10

How To Concatenate Variables In Windows Batch File

In this tutorial, we’ll explore how to concatenate variables in a Windows batch script. This technique is essential when you need to construct dynamic strings, build file paths, or format output for display or logging purposes.

Batch files consist of a sequence of DOS (Disk Operating System) commands executed by the Windows command-line interpreter. While basic, the language allows for powerful automation when mastered.
 

🛠 Concatenating Variables in Batch Files

In batch scripting, variable concatenation is as simple as placing the variables next to each other without any operator.
 
📌 Example: Concatenating Three Variables

@echo off

set www=StackHowTo

set "var1=----->"
set "var2=<-----"
set "str=%var1%%www%%var2%"

echo "%str%"

Output:

"----->StackHowTo<-----"

 
🔍 Explanation:

  • @echo off: Suppresses the command echoing for cleaner output.
  • set www=StackHowTo: Defines the core string to wrap.
  • set “var1=—–>”: Defines a prefix. Using quotes helps avoid trailing whitespace issues.
  • set “var2=<-----": Defines a suffix.
  • set “str=%var1%%www%%var2%”: Concatenates all three variables into a single string.
  • echo “%str%”: Displays the final result wrapped in quotes.

 

🧠 Best Practices

Quote your set statements: This avoids accidental inclusion of whitespace or special characters that can corrupt your variables.

set "var=Some Value"  :: Correct
set var=Some Value    :: Risky (might include trailing spaces)

Use enabledelayedexpansion if you’re modifying or building strings inside code blocks:

setlocal enabledelayedexpansion
set "part1=Hello"
set "part2=World"
set "combined=!part1! !part2!"
echo !combined!

 

✅ Summary

Concatenating strings in batch files is simple and powerful. By directly joining variables and maintaining clean coding practices, you can build dynamic commands, paths, and output formats essential for automation and scripting tasks.
 

Leave a Reply

Your email address will not be published. Required fields are marked *