24

There are several ways google throws at me for checking if a file is empty but I need to do the opposite.

If (file is NOT empty)

do things

How would I do this in batch?

4 Answers 4

28
for /f %%i in ("file.txt") do set size=%%~zi
if %size% gtr 0 echo Not empty
Sign up to request clarification or add additional context in comments.

5 Comments

returns: >>unexpected 0
@Tertium - The fix is to add set size=0 on the line before the for loop.
@Tertium I think you forgot the double quotes in for /f %%i in ("file.txt") - that's what I did and adding them back fixed the problem
Quick fix for if that returns an empty result, but a leading 0, like: if 0%size% GTR 0 echo Not empty
This solution not work in windows 10
9

this should work:

for %%R in (test.dat) do if not %%~zR lss 1 echo not empty

help if says that you can add the NOT directly after the if to invert the compare statement

1 Comment

shouldn't there be a Switch after if like: for %%R in (test.dat) do if /i not %%~zR EQU 0 echo not empty
4
set "filter=*.txt"
for %%A in (%filter%) do if %%~zA==0 echo."%%A" is empty

Type help for in a command line to have explanations about the ~zA part

Comments

4

You can leverage subroutines/external batch files to get to useful parameter modifiers which solve this exact problem

@Echo OFF
(Call :notEmpty file.txt && (
    Echo the file is not empty
)) || (
    Echo the file is empty
)
::exit script, you can `goto :eof` if you prefer that
Exit /B


::subroutine
:notEmpty
If %~z1 EQU 0 (Exit /B 1) Else (Exit /B 0)

Alternatively

notEmpty.bat

@Echo OFF
If %~z1 EQU 0 (Exit /B 1) Else (Exit /B 0)

yourScript.bat

Call notEmpty.bat file.txt
If %errorlevel% EQU 0 (
    Echo the file is not empty
) Else (
    Echo the file is empty
)

1 Comment

This worked great for me. I switched it around so it was called empty rather than notEmpty, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.