为什么设置时,此批变量甚至从来没有改变? [英] Why does this batch variable never change even when set?

查看:131
本文介绍了为什么设置时,此批变量甚至从来没有改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@echo off
SET first=0
FOR %%N IN (hello bye) DO (
SET first=1
echo %first%
echo %%N
)

看来这个变量第一始终是0。为什么?

It seems that the variable "first" is always 0. Why?

推荐答案

通过批处理文件,变量当他们的命令读取拓展 - 所以这将是很快的执行。在这一点上,它不再说回声%首%,其字面意思是呼应0 ,因为这是值在膨胀的点。

With batch files, variables are expanded when their command is read - so that would be as soon as the for executes. At that point, it no longer says echo %first%, it literally says echo 0, because that was the value at the point of expansion.

要解决这个问题,你需要用周围的变量名使用延迟扩展!而不是 - 所以这将是第一呼应!。这可能需要(后仅用/ V参数启动的cmd.exe,或在批处理文件的开头使用 SETLOCAL enabledelayedexpansion ECHO OFF )。

To get around that, you need to use delayed expansion by surrounding your variable name with ! instead of % - so that would be echo !first!. This may require you to start cmd.exe with the /V parameter, or use setlocal enabledelayedexpansion in the beginning of your batch file (just after echo off).

如果您键入设置/?,你会在输出的末尾看到这样一个更详细的解释。

If you type set /?, you'll see a much more detailed explanation of this at the end of the output.

这篇关于为什么设置时,此批变量甚至从来没有改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆