Friday, October 16, 2009

Checking for Existence of Variables and Parameters

Sometimes it's necessary to check in a batch file whether a certain variable is assigned. For example, it's useful when you need to check for some condition in "procedure" under certain label from main batch script. The usual way to check for existence looks like this:
if defined %VARIABLE% echo Variable exists!
But if you try to perform the same trick with parameters given to your batch script while its execution, you will be surprised. Code like
if defined %3 echo Parameter defined!
will not work correctly.
So what should one do to check whether certain parameter is passed to the batch file? The perfect solution is to compare the value of this parameter to empty string:
if "%1"=="" echo Help on parameters...
It's necessary to perform such check for existence of certain parameters if they are expected by your batch file. You should show short summary about the parameters of your batch file if there are less parameters than you expected. This simple technique will make your script more friendly. Even if one day you forget what parameters you need pass to it, you wouldn't read its code once more to remember them.

No comments:

Post a Comment

Translate