0

(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 start
:correct
echo correct
timeout 2 >nul /nobreak
goto start

If I just press enter, without any input, it tells me correct. Why? how can I prevent this? Is my syntax incorrect?

Also, If I press space, then enter, the batch file quits. It tells me in that split second screen the error (something like):

Goto was unexpected at this time

Which leads me to believe that I didn't give an instance/define the [space] key, but I cut out the spaces in the first instance. Wouldn't this mean that everything that didn't match the specific criteria

if %x%==1 goto correct

would just continue on in the script, since it's value didn't meet the one described in the given instance?

2 Answers2

2

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.

Magoo
  • 77,302
  • 8
  • 62
  • 84
1

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).

Gary
  • 13,303
  • 18
  • 49
  • 71