Batch file: environment variable "if" string test

5,959

I've created two batch files: b1.cmd and b2.cmd which follow. First, b2.cmd which sets your variables as described:

set today2=101415
set firstmonday=110215

Then b1.cmd which performs as desired:

@echo off
call b2.cmd
echo today=%today2%
echo firstmonday=%firstmonday%
if "%today2%"=="%firstmonday%" (
    goto go
) else (
    goto end
)
:go
echo at go
goto :EOF
:end
echo at end
Share:
5,959

Related videos on Youtube

Keith
Author by

Keith

Updated on September 18, 2022

Comments

  • Keith
    Keith over 1 year

    In a batch file, I'm calling another batch file to set a number of date environment variables.

    The data variables set properly and I can call them.

    However, in this instance, I need to compare two of these environment variables and determine if they are the same in order to conditionally launch the rest of the batch (or skip to end/exit).

    However, I cannot seem to get the conditional to execute the test (comparison) of the two environment variables.

    These are defined as %today2% (today's date set as MMDDYY) and %firstmonday%, which is a calculated first Monday of the month and set as MMYYDD). When run today (October 14, 2015), these return 101415 and 110215.

    I am then attempting to test these in the following way:

    if %today2%==%firstmonday% goto GO else END
    

    However, the test seems to be completely ignored -- the test always proceeds to GO regardless.

    If I echo %today% and %firstmonday% they are of course different, but somehow the test evaluates to true and executes.

    If I'm not explaining myself clearly, please let me know and I'll try to do a better job of it. I'm rather a novice when it comes to this, but have mucked around with it for a while and cannot seem to figure out the logic flaw.

    • AFH
      AFH over 8 years
      If you type if /? it gives examples of the correct syntax when there is an else clause: indeed it gives your example as an instance of a command that does NOT work, together with two working versions. Because the else syntax is inelegant, I find it easier to reverse the test, as in if not %today2%==%firstmonday% goto END, with the following line as the GO code.
    • Naidim
      Naidim over 8 years
      You have to ..else goto END and have :END after your :GO marker, as it currently just going to the next line.