Monday, 2 February 2009

Late Variable Binding in Batch Files

This is something that I am sure makes sense if you understand it, but for me it is just confusing..

Lets say that you are developing a batch file and you wan to set up a variable, you would think that if on one like you set it, the next line you can use it… but oh nooo, you have to wait…. was this feature written by Home Affairs ?

Check this batch file:

rem notice that we define TEST in the if statement, but it does not display...

if 1 == 1 (
Set TEST="test"
echo %TEST% )



rem Notice that we can use it now

if 1 == 1 (
echo %TEST% )

pause


Now like me you might expect on the first line to see the output test, but you only see it on the second.



image



The only thing I can reason ( it is just not worth researching, so I am guessing here ) is that because I am in a control structure, if , it has already set up its “stack” as some kind of optimization, so when I creating the TEST variable I am creating in the global stack which is why I can use it later, but this local stack inside the if cannot be updated.



Moral of the story



If you want to set a variable and use it then don’t do in inside a control statement. To make the first example work it would be as simple as :



Set TEST="test"
if 1 == 1 (
echo %TEST% )



Update

You can find more specific details here on SO

No comments:

Post a Comment