Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

batch file fails to set variable in IF clause

The following code is not updating Run to equal N even though the match occurs. this means I'm not dropping into the CALL code. Am i missing something here?

SET Run=Y

REM Check current files date/time information and establish if the file has been present too long in the directory
REM Skip first 4 lines as header information not required

FOR /f "tokens=1-5 skip=4 delims= " %%G IN ('dir /OD "%SRCH_CRITERIA% "') DO (

    ECHO "Params to processFile:  " %%G %%H %%I ""%%K""
    IF %%K.==.  ( 
        ECHO "K:nothing"
        SET Run=N
        ECHO %Run%
    ) 

    IF %%K==free (
        ECHO "K:FREE"
        SET Run=N
        ECHO %Run%
    ) 

    ECHO %Run% RUN
    IF %Run%=="Y" (
        CALL :processFile "%%G" "%%H" "%%I" "%%K"
    )   
)
like image 554
sapatos Avatar asked Dec 30 '09 02:12

sapatos


1 Answers

You need to use the delayed expansion option of cmd.exe.

At the top of your script, put:

setlocal enableextensions enabledelayedexpansion

and then put:

endlocal

at the bottom.

Then you need to use !Run! instead of %Run%.

The reason your code is not working is that the entire FOR statement (including the commands within it) is evaluated when it's encountered. That's the point where the %Run% variables are expanded.

By using deferred expansion, you don't expand them until they're actually needed (after you've set them within the block).

You can see the difference in this script:

@echo off
setlocal enableextensions enabledelayedexpansion

set xx=0
for %%i in (a b c d) do (
    echo %%i
    set /a "xx = xx + 1"
    if %xx%==3 echo yes for normal
    if !xx!==3 echo yes for delayed
)

endlocal

which outputs:

a
b
c
yes for delayed
d

You'll notice that the check with %xx% does not work because that was evaluated when the for statement started (and xx was 0). The delayed-expansion !xx! does work since that is evaluated each time through the loop.

like image 122
paxdiablo Avatar answered Sep 18 '22 22:09

paxdiablo