You are not logged in.
Hi,
I would like to gain a status (confirmation indeed ) unsuccesfully performed the for loop which wasn't iterated at all due to the fact that it is based on zero-bytes file. I want to use echo %errorlevel% but every time I try to use it I get success status = 0. Where I have to place echo %errorlevel% to get a proof?
@echo off
setlocal EnableDelayedExpansion
(
for /F "delims=; eol=#" %%i in (C:\zero_byte.txt) do ( echo sometext )
) || (
echo "the for loop wasnt iterated and exited with return code != 0"
)
Command after a negative conditional conjunction is executed, therefore I know what was the status of the first block in the script.
Greetings
Offline
You can set a variable inside of the loop to determine if it was run or not.
@echo off
setlocal enabledelayedexpansion
set "loop_iterated=false"
for /F "delims=; eol=#" %%A in (C:\zero_byte.txt) do (
set "loop_iterated=true"
echo Some text
)
if "!loop_iterated!"=="false" (
echo The for loop was not iterated.
)
Offline
Good point, thanks!
Offline
This example is posted below Table 5 at this answer.
(for /F "options" %%a in (input.txt) do echo %%a) || rem
if errorlevel 1 echo Previous FOR didn't processed any value
Antonio
Offline
Thanks, after I read about ErrorLevel rules here at ss64.com/nt/errorlevel.html where there is a piece of information about for loop not affecting errorlevel (sorry I missed that) I supplement the rest of knowledge from Stackverflow.
Offline
@Shadow Thief: FYI There's no real need to invoke delay expansion in your solution, this should work just fine.
@echo off
set "loop_iterated=false"
for /F "delims=; eol=#" %%A in (C:\zero_byte.txt) do (
set "loop_iterated=true"
echo Some text
)
if "%loop_iterated%"=="false" (
echo The for loop was not iterated.
)
In fact, you can still sidestep delayed expansion even if you happen to be nested in parentheses.
@echo off
if 1 EQU 1 (
set "loop_iterated="
for /F "delims=; eol=#" %%A in (C:\zero_byte.txt) do (
set "loop_iterated=1"
echo Some text
)
if not defined loop_iterated (
echo The for loop was not iterated.
)
)
cmd | *sh | ruby | chef
Offline
@bluesxman, all parentheses except for those dedicated for do command block (set and echo) are used to make code more readable? I am asking because without if condition and mentioned parentheses it still works. Of course, parentheses for second echo (the for loop was not iterated) are required because it is not one line command i.e. if not defined loop_iterated echo The for loop was not iterated, right?
Offline
I just kept delayed expansion enabled because it was already enabled in the original post (and it's usually a good idea to have it on anyway)
Offline