(I\'ll use this script as an example)
@echo off
:start
cls
set /p x=enter the password:
if %x%==1 goto correct
echo incorrect
timeout 1 >nul /nobreak
goto sta
Change this:
if %x%==1
To this:
if "%x%" EQU "1"
The quotes encase the variable so you always have a valid string to compare, then you have to do the same to what you're comparing it to for consistency. EQU
is another way to compare strings (check out if /?
for other operators).
Common problem - most, but not all of which is solved by
if "%x%" EQU "1"...
If you are entering a string with a set/p
, then there's no saying that the data entered doesn't contain Spaces. The way to get over that is to "enclose the strings on both sides of the comparison operator in quotes"
- that is, double-quotes 'not single quotes'
The other problem is more subtle. Pressing just Enter leave x
unchanged - it does not "set" it to an empty string. Hence, if you start your procedure and press Enter then the "contents" of x
will be indeed be nothing - and the instruction, as has been mentioned, will be resolved to if ==1 goto correct
, hence the syntax error - and that same syntax error would occur for an entry of spaces.
Suppose you instead enter something - say 2
. x
is now set to 2
, so the if
statement is happy and decides to not take the branch, you get the next instruction executed, and return for another input.
Suppose you now enter 1
. if
is still happy, takes the branch, shows "correct" and waits for another input.
If you then simply press Enter x
will remain unchanged, so the correct
branch will be taken.
So what is actually happening is that x
after Enter repeats the last input.
To get over this problem, you need to execute
set "x="
set /p x=enter the password:
which clears x
first. The set "var=value"
syntax ensures that any trailing spaces on the batch line are not included in the value assigned to var
.
You can use this characteristic to assign a default value,
set "x=hello"
set /p x=enter the password:
would set x
to hello
if the user simply replies Enter to your prompt.