23

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

27
for /f %%i in ("file.txt") do set size=%%~zi
if %size% gtr 0 echo Not empty
4
  • 1
    returns: >>unexpected 0
    – Tertium
    Mar 11, 2017 at 20:11
  • @Tertium - The fix is to add set size=0 on the line before the for loop. May 12, 2017 at 18:52
  • @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
    – im_chc
    May 22, 2019 at 8:57
  • Quick fix for if that returns an empty result, but a leading 0, like: if 0%size% GTR 0 echo Not empty Sep 24, 2019 at 1:51
8

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
  • shouldn't there be a Switch after if like: for %%R in (test.dat) do if /i not %%~zR EQU 0 echo not empty Jan 16, 2018 at 9:49
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

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
  • This worked great for me. I switched it around so it was called empty rather than notEmpty, though.
    – kindall
    Jul 15, 2021 at 3:16

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.