批处理脚本中的问题读取用户输入

jch*_*jch 3 windows cmd user-input batch-file

我使用set /p下面的内容来读取用户输入它似乎在if块之外工作,但如果块不起作用则在内部.当我第二次运行脚本时,if块中的用户输入打印先前的用户输入.

测试脚本:

@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%
Run Code Online (Sandbox Code Playgroud)

谢谢

Joe*_*oey 10

阅读延迟扩展help set.

默认情况下,%foo%cmd分析行时会扩展环境变量().在这种情况下,一行是一个单独的语句,可以包括一个完整的括号内的块.因此,一个块的解析后,环境变量的所有出现替换为它的价值在解析时.如果您更改块中的变量并在之后再次使用它,您将看到旧值,因为它已被替换.

延迟扩展,可以启用

setlocal enabledelayedexpansion
Run Code Online (Sandbox Code Playgroud)

导致环境变量标记有感叹号而不是百分号(!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!
)
Run Code Online (Sandbox Code Playgroud)