Batch file: environment variable "if" string test
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
Related videos on Youtube
Keith
Updated on September 18, 2022Comments
-
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 over 8 yearsIf you type
if /?
it gives examples of the correct syntax when there is anelse
clause: indeed it gives your example as an instance of a command that does NOT work, together with two working versions. Because theelse
syntax is inelegant, I find it easier to reverse the test, as inif not %today2%==%firstmonday% goto END
, with the following line as theGO
code. -
Naidim over 8 yearsYou have to
..else goto END
and have:END
after your:GO
marker, as it currently just going to the next line.
-