The code is,
set VAR=before if '%VAR%' == 'before' ( set VAR=after; echo %VAR% )
What will the preceding Windows .bat file code segment display? Why? (i.e. why doesn’t it behave as you might first think)?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Obviously, you’d think the output would be ‘after’, given that we reset the env variable inside the loop.
But the output will actually be ‘before’. The reason is that variable substitution is done in .bat files by the interpreter when a command is read, rather than when it’s executed. So, for the compound statement, the variables in the body are evaluated when the if statement is first encountered.
You can make this work by using delayed environment variable expansion (need to enable it). If it’s enabled, you can then do:
You can enable delayed environment variable expansion using the /v option when starting cmd.exe.
[Backstory–many of us still use legacy .bat files to drive things like make procedures, etc. Obviously there are better scripting tools, but not always an option to use them. I ran into this issue a while back and recently found two other people who had pulled their hair out over the same thing. So it’s useful to understand how the interpreter does variable substitution].