views:

102

answers:

1

hi,

i use set /p below to read user input it seems to work outside the if block but the one inside if block doesn't work. When i run the script second time the user input in the if block prints the previous user input.

test script:

@echo off
set cond=true
echo %cond%
if %cond%==true (
echo "cond is true"
REM the below input doesn't work
set /p name1="enter your name"
echo name is: %name1%
)

REM it works here
set /p name2="enter your name"
echo name is: %name2%

thank you

+3  A: 

Read up on delayed expansion in help set.

By default environment variables (%foo%) are expanded when cmd parses a line. And a line in this case is a single statement which can include a complete parenthesized block. So after parsing of a block all occurrences of environment variables are replaced with its value at the time of parsing. If you change a variable in the block and use it after that again, you will see the old value, simply because it has already been replaced.

Delayed expansion, which can be enabled with

setlocal enabledelayedexpansion

causes environment variables marked up with exclamation marks instead of percent signs (!foo!) to be evaluated directly before executing a statement which is after parsing.

@echo off
setlocal enabledelayedexpansion enableextensions
set cond=true
echo %cond%
if %cond%==true (
echo "cond is true"
REM the below input does work now
set /p name1="enter your name"
echo name is: !name1!
)
Joey
You can also start `CMD.EXE` using the `/V:ON` switch.
NealB
@neal: For most batch files that's not a viable option.
Joey
thank you very much...this is new to me ..do you know suggest any good resource where i can read about it?
JCH
one more question this must work on all flavours of windows right? xp,vista,win7,etc
JCH
Works since NT 4. And there are several batch file resources out there; http://robvanderwoude.com/ and http://ss64.com/ spring to mind. However I usually just need the built-in documentation and learned most of what I know by experimenting and solving problems.
Joey