批量变量被破坏

时间:2016-03-21 06:38:33

标签: batch-file

我正在批量制作聊天室的东西。不幸的是,文件无法存储变量。这是我的代码

@echo off
color b
Title Messanger
:top
echo Are you hosting the chat?
set /p host="Yes or no>"
if /i "%host%"=="yes" (
    set /p port="Port>"
    rem This would normally listen for connections
    echo Listening for connections on port %port%
    pause
 )
if /i "%host%"=="no" (
    echo Who is hosting this chat?
    set /p ip="Ip>"
    set /p port="Port>"
    echo ----------------CHAT----------------
    rem This would normally connect to the ip and port
    echo %ip% %port%
 )
echo Error.
pause
goto top

我不知道你是否得到相同的结果,但只看到没有变量的消息。输出:

Are you hosting the chat?
Yes or no>yes
Port>8080
Listening for connections on port
Press any key to continue . . .

在此之后,它会执行ad echos错误并转到文件的开头

1 个答案:

答案 0 :(得分:1)

解决方案有两个方面:

1)您需要将setlocal enabledelayedexpansion添加到脚本的开头。像这样:

@echo off
setlocal enabledelayedexpansion
color b
Title Messanger

(注意第2行)

2)然后,在IF块内,您需要使用!代替%来解决变量,如下所示:

if /i "%host%"=="yes" (
    set /p port="Port>"
    rem This would normally listen for connections
    echo Listening for connections on port !port!
    pause
 )

(注4)

说明

因为%ip%%port%在子句内(即在括号内),所以在块内的实际代码执行之前捕获它们的值。在解释器进入IF块之前,它会在执行此操作之前捕获%port%的值(在进入实际块之前它不存在)。所以,虽然看起来就像你的代码正在运行

echo Listening for connections on port %port%

实际运行的是

echo Listening for connections on port 

(注意空格。%port%在进入括号内的块之前被%port% 的值替换 - 这是一个空值。

使用经过修改然后在一个块内重新使用的变量的解决方案是启用延迟扩展,然后使用!符号而不是%来引用它们。