Batch file tips and horrors
Dude, it seems that some things are made by sadists...
It can't be explained otherwise...
Before explaining the horrors I will give you a tip that I think you will find useful.
Typing the following line in a BAT file:
SET /p VAR=Please enter value:
Will give you a sweet prompt so that you can enter the value to be used in the batch file!!!
Wow64!!!
I've been looking for this for years! And it has been there in the friggin' help for SET who knows for how long.
Moreover SET has the /a switch that can evaluate expressions which means that you can use it to create simplistic loops in a batch file, with a statement like this:
SET /a VAR=%VAR%+1
And as a bonus if you do SET /a 5*4 on the command line you get to use the shell as a quick calculator for integer arithmetic :-)
Now let's go to the horrors...
Take a look at this trivial batch file:
@ECHO OFF
SET /p VAR=Give me VAR value:
echo VAR=%VAR%
if EXIST C:\nul (
SET VAR=C:\%VAR%
echo VAR=%VAR%
)
echo VAR=%VAR%
The if condition is made so that it succeeds (for most people).
If you enter 123 at the prompt, what do you expect to get printed?
VAR=123
VAR=C:\123
VAR=C:\123
Right?
Wrong... And here comes the horror!
The batch file outputs the following:
VAR=123
VAR=123
VAR=C:\123
What the heck???
To cut a long story short, the SET statement inside the IF actually takes place, but its results are NOT visible inside the IF!!! Instead the previous value is used throught the statements within the if.
I tried several things to make a SET statement that takes place within an IF to make its results visible to the rest of the statements. Be my guest. It seems however that the interpreter is reading and translating all the statements inside the IF in a single operation, so any updated variables do not get reflected to the code.
For the time being right the code like this:
@ECHO OFF
SET /p VAR=Give me VAR value:
echo VAR=%VAR%
if not EXIST C:\nul goto AFTER_IF
SET VAR=C:\%VAR%
echo VAR=%VAR%
:AFTER_IF
echo VAR=%VAR%
Enjoy!
Dimitris Staikos
Comments