1.

Solve : Win/Batch: Question in DOS IF command?

Answer»

Hi,

I got following output: -

ERRORLEVEL is 9009
task_flag is 9009
error !!!

with the following CODE:-
@echo off
set task=0
abd ^/? > nul
IF %ERRORLEVEL% NEQ 0 (
CLS
SET task=%ERRORLEVEL% )
echo errorlevel is %errorlevel%
echo task_flag is %task%
echo error !!!
:end
pause
exit
===========================================

However, I got the following output: -
errorlevel is 9009
task_flag is 0
error !!!

with the following code: -
@echo off
set task=0
abd ^/? > nul
IF %ERRORLEVEL% NEQ 0 (
CLS
SET task=%ERRORLEVEL%
echo errorlevel is %errorlevel%
echo task_flag is %task%
)
echo error !!!
pause
exit
============================================

Different value of %task% displayed

Any ideal ?



Quote from: lwkt on SEPTEMBER 14, 2009, 10:45:53 PM

different value of %task% displayed

if you set and read a variable inside parentheses (brackets) you need to use "delayed expansion". Otherwise it will either keep the value it had before the parentheses or if it had none, be null.

1. put this line before the parenthetical structure (e.g. at the start of the batch file

setlocal enabledelayedexpansion

2. A variable which may be set or changed inside parentheses needs to use exclamation marks ! and not percent symbols %

@echo off
setlocal enabledelayedexpansion
set task=0
abd ^/? > nul

REM %ERRORLEVEL% was set outside the parentheses
REM so it keeps its value
REM %task% was set to 0 and retains that value
REM unless you use delayed expansion and
REM exclamation marks

IF %ERRORLEVEL% NEQ 0 (
CLS
SET task=%ERRORLEVEL%
echo errorlevel is %errorlevel%
echo task_flag is !task!
)
echo error !!!
pause
exitGot it. Thanks.

Where can I found the information about "delayed expansion" and "A variable which may be set or changed inside parentheses needs to use exclamation marks ! and not percent symbols %"Google
?Billrich attacking me again, for his own painfully obvious reasons. When we FEEL that Googling is more useful than writing YADEE (yet another delayed expansion explanation) (I have done about 6) we say so.

Here is a good link however.

http://www.robvanderwoude.com/variableexpansion.php


Discussion

No Comment Found