开发者

problem in batch script read user input

开发者 https://www.devze.com 2023-01-02 23:51 出处:网络
i use set /p开发者_JAVA技巧 below to read user input it seems to work outside the if block but the one inside if block doesn\'t work.

i use set /p开发者_JAVA技巧 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


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!
)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号