Windows 10

How To Compare Strings In Batch Files

In this tutorial, we will learn how to compare strings within Windows batch files using the == operator. Batch files consist of sequences of DOS (Disk Operating System) commands executed by the Windows command interpreter (CMD), useful for automating repetitive tasks and scripting.

String comparison is a fundamental operation when writing batch scripts that require conditional logic based on variable values.
 

🛠 How to Compare Strings in Batch Files

To compare two strings in a batch file, you can use the IF statement along with the == operator. Here’s an example that demonstrates comparing variables and conditionally displaying messages:

@echo off
SetLocal EnableDelayedExpansion

set var1=Hello
set var2=Hello
set var3=HELLO

if !var1! == !var2! echo Equal
if !var1! == !var3! (
    echo Equal
) else (
    echo Not Equal
)

Output:

Equal
Not Equal

 

🔍 Explanation:
  • SetLocal EnableDelayedExpansion: Enables delayed environment variable expansion, allowing variables to be evaluated correctly inside code blocks (parentheses).
  • set var1=Hello, set var2=Hello, set var3=HELLO: Defines three string variables.
  • if !var1! == !var2! echo Equal: Compares var1 and var2; prints Equal if they match.
  • if !var1! == !var3! (echo Equal) else (echo Not Equal): Checks if var1 and var3 are equal; prints Not Equal because comparison is case-sensitive.

 

✅ Summary

Using the == operator in batch files is a straightforward way to compare strings and implement conditional logic. Remember to enable delayed variable expansion when working inside code blocks and consider case sensitivity according to your use case.
 

Leave a Reply

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