Set variable depends on if

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
darioit
Posts: 230
Joined: 02 Aug 2010 05:25

Set variable depends on if

#1 Post by darioit » 06 Aug 2010 07:17

Hello everybody,

Why this variable doesn't work?

Code: Select all

@ECHO OFF

SET AA=******************
SET C1=THIS IS THE RIGHT LINE
SET C3=.................

set cnt_record=1
set rec_tot=2

CALL :check
GOTO:EOF

:check
IF %rec_tot% NEQ %cnt_record% (
SET C1=WRONG LINE
SET E1=WRONG RECORDS %cnt_record%
SET E2=WRONG RECORDS %rec_tot%
ECHO.%AA% >> E:\output.txt
ECHO.%C1% >> E:\output.txt
ECHO.%E1% >> E:\output.txt
ECHO.%E2% >> E:\output.txt
) ELSE (
ECHO.%AA% >> E:\output.txt
ECHO.%C1% >> E:\output.txt
ECHO.%C3% >> E:\output.txt
)

GOTO:EOF


Thanks

avery_larry
Expert
Posts: 391
Joined: 19 Mar 2009 08:47
Location: Iowa

Re: Set variable depends on if

#2 Post by avery_larry » 06 Aug 2010 11:02

All variables inside the parentheses will be evaluated at the time the entire block of code is called -- NOT after the variables' values are changed.

Classic reason to use delayedexpansion:

Code: Select all

@ECHO OFF
setlocal enabledelayedexpansion

SET AA=******************
SET C1=THIS IS THE RIGHT LINE
SET C3=.................

set cnt_record=1
set rec_tot=2

CALL :check
GOTO:EOF

:check
IF %rec_tot% NEQ %cnt_record% (
   SET C1=WRONG LINE
   SET E1=WRONG RECORDS %cnt_record%
   SET E2=WRONG RECORDS %rec_tot%
   ECHO.%AA% >> E:\output.txt
   ECHO.!C1! >> E:\output.txt
   ECHO.!E1! >> E:\output.txt
   ECHO.!E2! >> E:\output.txt
   ) ELSE (
      ECHO.%AA% >> E:\output.txt
      ECHO.%C1% >> E:\output.txt
      ECHO.%C3% >> E:\output.txt
)

GOTO:EOF

darioit
Posts: 230
Joined: 02 Aug 2010 05:25

Re: Set variable depends on if

#3 Post by darioit » 06 Aug 2010 12:10

oh thanks, I have activate only "setlocal enableextensions", thanks for the help, now it works very cool

Post Reply