# Solved: Empty environment variable expansion fails



## rettug (Nov 12, 2009)

Ok, this one's killing me. I've used expressions like

*if x%VALUE% == x*

to test for empty (really, undefined) environment variables for years. It's suddenly broken. That is, even from the command line

*set VALUE=*
*if x%VALUE% == x echo Empty*

displays nothing. You can see 'why' with an echo:

*set VALUE=*
*echo %VALUE%*

displays the string

*%VALUE%*

Now I know I can use

*if not DEFINED VALUE*

instead, but that prevents me from using %VALUE% for both actual and null substrings, which is really handy.

Note that batch parameter substitution still works, e.g.

*call :sub*
*goto :eof*
*:sub*
*if x%1 == x echo Empty*
*goto :eof*

displays Empty as usual.

Any ideas? I'm running XP Pro SP2. CMD reports the version as Microsoft Windows XP [Version 5.1.2600]


----------



## TheOutcaste (Aug 8, 2007)

That's normal behavior when typing those commands at a command prompt. Been that way since NT 4.0, if not earlier.

At the Command Line, if a variable is undefined, Echo will echo exactly what you typed, it doesn't substitute a null value for the undefined variable. Same with If.
It only works if the statements are executed in a batch file.

If it's not working when executed from within a batch file, I haven't a clue, as it still works for me. Assuming you've rebooted, make sure you are opening the real cmd.exe by typing *c:\Windows\System32\cmd.exe* into the run box.
Run *SFC /SCANNOW* to check for corrupted system files.

This file works as expected for me, just tested on NT4.0, Win2K, XP-SP0, XP-SP2, XP-SP3, Win7:

```
set VALUE=
echo %VALUE%
if x%VALUE% == x echo Empty
```


```
E:\Scripts>EVTest.cmd

E:\Scripts>set VALUE=

E:\Scripts>echo
ECHO is on.

E:\Scripts>if x == x echo Empty
Empty

E:\Scripts>
```
Since value is undefined, the echo statement simply echos the current echo setting.
Also tested with Command Extensions disabled.

If your variable contains spaces you will get an error:

```
Set VALUE=TEST DATA
If x%VALUE%==x Echo Empty
```
Will tell you *DATA was unexpected at this time.*
You should use this format instead:

```
Set VALUE=TEST DATA
If "%VALUE%"=="" Echo Empty
```


----------



## rettug (Nov 12, 2009)

Right you are. A different bug led me down the path of testing the undefined variable from the command line, and once I saw it echo the string - I never knew it did that! - I assumed it would do the same from within the batch file.

Thanks for your work on this, and your quick & knowledegeable response!


----------

