Unexpected behaviour of SET /P comm

Laavanya February 5, 2009 at 04:24:05
Specs: Windows XP
Hello guys,

I've been trying to write some code using dos commands, and i've been facing this strange

issue.The requirement is to check if a certain folder exists, and if it does, the user

would be given a choice to either overwrite the folder or leave it as it were.

I've written the following code to achieve the above:

IF EXIST C:\TEST (

@ECHO A DIRECTORY WITH THE SAME NAME "C:\TEST" ALREADY EXISTS.
SET /P USERINPUT="DO YOU WANT TO OVERWRITE THE EXISTING DIRECTORY (Y/N):"
) ECHO %USERINPUT%


The issue is, when I run this script multiple times, the value of the input variable %

USERINPUT% seems to persist.

For instance, if this script is run for the first time and user input is "y", the variable

%USERINPUT% echoes "y". Now if the script is run a second time on the same command window,

and the user input is "n", the variable %USERINPUT% still echoes "y". If this script is run

a third time, and one enters a "y", the variable %USERINPUT% would echoes a "n".

It thus seems that the vaue in the variable %USERINPUT% presists for a longer duration,

which is obvious not the desired result.

Could anyone throw any light on this issue? I need to get this to work so as to accept the

right values. I'am not sure what the issue is here.

Regards,
Laavanya


See More: Unexpected behaviour of SET /P comm

Report •


#1
February 5, 2009 at 04:29:56
It looks like the final ECHO is part of that IF statement. If that's the case, then move it out of the IF statement, as variable expansion happens before the entire statement is executed.

Report •

#2
February 5, 2009 at 04:55:36
Thanks Razor2.3.

I did take the final echo out of the if and it did work. However how do i get the following piece of code to work in that case, because the USERINPUT variable does not seem to receive the correct value.

IF EXIST C:\TEST (
@ECHO.
@ECHO A DIRECTORY WITH THE SAME NAME "C:\TEST" ALREADY EXISTS.

SET /P USERINPUT="DO YOU WANT TO OVERWRITE THE EXISTING DIRECTORY (Y/N):"

IF /I "%USERINPUT%"=="Y" (
DEL C:\TEST
MKDIR C:\TEST
@ECHO C:\TEST CREATED..
@ECHO.
PAUSE
) ELSE (
@ECHO.
@ECHO USER CHOSE TO NOT OVER WRITE AND KEEP THE EXISTING DIRECTORY.
@ECHO.
PAUSE
)
) ELSE (
@ECHO C:\TEST CREATED..
PAUSE
)


Report •

#3
February 5, 2009 at 06:05:00
You can't refer to a variable defined inside the same block sequence, i.e. a sequence of statements embraced by (). To do so you have to enable the delayed expansion of variables by coding at the beginning of your script

setlocal EnableDelayedExpansion

then mark the variable with ! instead of the usual %

IF /I "!USERINPUT!"=="Y" (

To know more about dynamic expansion type at prompt SET /?

Report •

Related Solutions

#4
February 6, 2009 at 02:10:41
Thanks IVO...that did it for me.


Report •


Ask Question