This is a common problem in a lot of scripting languages. The issue is that the variable names are expanded to their values before the line is executed. If the variable is left blank, the script will run the code:
if ==word (goto oh)
The two equal signs are not parsed as the equality operator because IF expects to find an item for comparison on both sides. Instead of (goto
, an operator such as EQU
is expected, and an error message will reflect that.
A similar problem will occur if the user enters a string containing spaces, e.g.:
if what I typed==word (goto oh)
This behaviour can be used for all sorts of dirty code. As an example, the condition will evaluate to true if the user enters 'word', but also if he enters '==word EQU ', in which case the line would be parsed as: if ==word EQU ==word (goto oh)
. Usually, we don't want to deal with those edge cases too extensively and can avoid the problem with blank variables by adding dummy characters, e.g.: if %a%dummy==%b%dummy
. This way, the syntax will be valid even if one (or both) of the variables are empty. In batch files, a particularly useful dummy character is the "-symbol, as it also prevents spaces from being parsed as delimiters. The following code should be significantly more robust:
if "%ui%"=="%word%" (goto oh)