Logan
Logan

Reputation: 1794

How to check for equality in batch script?

I am trying to find files with a specific date, but my equality isn't working as I think it is supposed to. Here is my batch file:

@echo off
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION

chdir /d T:

FOR /r %%i IN (*) do (
   echo %%i

   set FileDate=%%~ti
   echo Date: !FileDate!

   set year=!FileDate:~6,4!  
   echo year: !year!

   if !year! == 2009 (
      echo is 2009
   ) else (
      echo not 2009
   )
)

And when I run it, I get the following output:

T:\SomeFile.txt
Date: 09/11/2009 02:51 PM
year: 2009
not 2009

Can somebody please explain to me why the year is printing as 2009, but is not being considered as 2009 by the if check? Thanks and sorry for my batch-file noobery.

Upvotes: 4

Views: 10603

Answers (3)

aschipfl
aschipfl

Reputation: 34909

Instead of the == comparison operator which means string comparison, you could use the EQU operator -- if you have the command extensions enabled (see if /? and also cmd /?):

if !year! EQU 2009

This does numeric comparison, so whitespaces around either of the values have no effect.


However, to avoid any whitespaces to become part of variable values (in this case year contains two trailing spaces), you should use the following syntax of set:

set "year=!FileDate:~6,4!"

Since the quotes "" are around the entire expression, they do not become part of the value.

Upvotes: 5

Tin Chanh Le
Tin Chanh Le

Reputation: 1

Could you please try with (add /a):

set /a year=!FileDate:~6,4!

You can refer to: https://en.wikibooks.org/wiki/Windows_Batch_Scripting

Good luck ^^/

Upvotes: 0

Evan Graham
Evan Graham

Reputation: 398

It's actually a whitespace issue.

On this line you have additional whitespace at the end which is being added to the variable.

set year=!FileDate:~6,4!  

Upvotes: 1

Related Questions