Page 1 of 1

Move errorlevel in For Statement

Posted: 06 Nov 2021 22:14
by drgt

Code: Select all

for /f "usebackq delims=" %%i in (test.log) do move %%i "C:\path"
if errorlevel 1 goto zero
echo success
pause
exit
:zero
echo nothing to move
pause
exit
When test.log is 0 bytes (and maybe if cannot be found?) I would expect to see "nothing to move" BUT is not happening.
Why is that and how to modify?

Re: Move errorlevel in For Statement

Posted: 06 Nov 2021 22:57
by Squashman
The DO commands never execute because the file is empty so the FOR command has nothing to parse.

Re: Move errorlevel in For Statement

Posted: 07 Nov 2021 00:33
by drgt
I see.
So what is the workaround for the zero subroutine?

Re: Move errorlevel in For Statement

Posted: 07 Nov 2021 04:45
by aGerman
There is modifier ~z of FOR variables which expands to the size of a file.
Using if exist ... you can check the existence of a file.

Code: Select all

@echo off &setlocal
set "file=xyz.txt"

set "isgood="
if exist "%file%" for %%i in ("%file%") do if %%~zi neq 0 set "isgood=1"

if defined isgood (echo OK) else echo not found or zero size
pause
Steffen

Re: Move errorlevel in For Statement

Posted: 08 Nov 2021 10:56
by Aacini
You may use the trick described at end of this answer (under Table 5 - Commands or features that set the Exit Code):

Code: Select all

(for /f "usebackq delims=" %%i in (test.log) do move %%i "C:\path") || rem
if errorlevel 1 goto zero
echo success
pause
exit
:zero
echo nothing to move
pause
exit

Antonio

Move errorlevel in For Statement

Posted: 09 Nov 2021 02:51
by drgt
That is really a nice TRICK!

By the way, I thought the open parenthesis before "for" was a typo BUT IS REQUIRED for it to work correctly, otherwise it works like in post 1.
Squashman wrote:
06 Nov 2021 22:57
The DO commands never execute because the file is empty so the FOR command has nothing to parse.
On second thought, I would think that the "move nothing to target" would parse the errorlevel, and not the FOR...