windows 批处理脚本读取用户输入中的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3025147/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
problem in batch script read user input
提问by jch
i use set /pbelow 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.
我set /p在下面使用它来读取用户输入,它似乎在 if 块之外工作,但在 if 块内不起作用。当我第二次运行脚本时,if 块中的用户输入会打印上一个用户输入。
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
谢谢你
回答by Joey
Read up on delayed expansion in help set.
阅读help set.
By default environment variables (%foo%) are expanded when cmdparses 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.
默认情况下%foo%,cmd解析一行时会扩展环境变量 ( ) 。在这种情况下,一行是一个单独的语句,它可以包含一个完整的带括号的块。因此,在解析块后,所有出现的环境变量都将替换为其解析时的值。如果您更改块中的变量并在此之后再次使用它,您将看到旧值,因为它已被替换。
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 executinga statement which is afterparsing.
导致!foo!在执行解析后的语句之前直接评估用感叹号而不是百分号 ( )标记的环境变量。
@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!
)

