Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 723
Logan Avatar asked Oct 24 '25 22:10

Logan


2 Answers

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.

like image 100
aschipfl Avatar answered Oct 26 '25 23:10

aschipfl


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!  
like image 33
Evan Graham Avatar answered Oct 26 '25 23:10

Evan Graham