batch-filecmd

Need better way to compare empty/null variable in batch file


I know one way to test an empty batch file variable for an empty/null value, but I'm looking for a better way.

In windows batch files, a variable can be assigned an empty/null value by snarfing an empty file and assigning the contents to the variable as follows:

> set /p foo=<foo.txt

To detect this as an error condition, you can create an empty variable for comparison using this method, and if you do, the following will work:

> set /p foo1=<foo.txt
> set /p foo2=<foo.txt
> if "%foo1%" == "%foo2%" ( echo same ) else (echo different)
same

However, the only method I know of to create an empty file for this purpose in a batch file is to use the touch command via git bash. Such a file can be created using explorer (right click, "New Text Document"), but I would prefer a method that can be used in a batch file that doesn't involve git-bash and uses only windows commands.

Better yet, I'd prefer a method that doesn't require the creation of an empty file to create a defined but empty variable. But I haven't found any method that works.

For instance, the following does not work:

if "%foo1%" == "" ( echo same ) else (echo different) different

Nor does:

> set "foo2="
> if "%foo1%" == "%foo2%" ( echo same ) else (echo different)

Because foo2 is not empty, it is undefined.

Existing questions fail to answer this question, and many of them falsely assume that it is impossible to have an empty defined variable.


Solution

  • Okay, there seems to be only one answer.

    The behavior I described was very consistent across many tests and many hours, and when I searched for an answer all I could find was people telling me: this is impossible!

    Well, I finally revisited it, and tried to reproduce it, and it doesn't work anymore. I haven't been able to reproduce this behavior.

    So, the answer seems to be, if this happens to you, reboot, cross your fingers, and hope it goes away.

    Apologies to all of you who were as frustrated with me as I was frustrated with you.