Move errorlevel in For Statement

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
drgt
Posts: 144
Joined: 21 Sep 2010 02:22

Move errorlevel in For Statement

#1 Post by drgt » 06 Nov 2021 22:14

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?

Squashman
Expert
Posts: 4360
Joined: 23 Dec 2011 13:59

Re: Move errorlevel in For Statement

#2 Post by Squashman » 06 Nov 2021 22:57

The DO commands never execute because the file is empty so the FOR command has nothing to parse.

drgt
Posts: 144
Joined: 21 Sep 2010 02:22

Re: Move errorlevel in For Statement

#3 Post by drgt » 07 Nov 2021 00:33

I see.
So what is the workaround for the zero subroutine?

aGerman
Expert
Posts: 4326
Joined: 22 Jan 2010 18:01
Location: Germany

Re: Move errorlevel in For Statement

#4 Post by aGerman » 07 Nov 2021 04:45

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

Aacini
Expert
Posts: 1730
Joined: 06 Dec 2011 22:15
Location: México City, México

Re: Move errorlevel in For Statement

#5 Post by Aacini » 08 Nov 2021 10:56

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

drgt
Posts: 144
Joined: 21 Sep 2010 02:22

Move errorlevel in For Statement

#6 Post by drgt » 09 Nov 2021 02:51

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...

Post Reply