如何在if块内实现赋值? [英] How to realize an assignment within the if block?

查看:67
本文介绍了如何在if块内实现赋值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

直到if块之后才实现在if块中进行的赋值(即set语句).因此,换句话说,您不能依赖if块内的变量分配.该如何解决?

解决方案

IF或FOR块中的分配立即实现.没有正确实现的是用百分号包围的变量值的替代.您必须注意,在执行该行之前替换了%variable%值.例如:

  set var =旧值set var =新值&回声%var% 

先前的命令显示:旧值".解决此问题的方法是通过延迟扩展,即,将变量用感叹号代替百分号,并在开始处添加 setlocal ... 命令.那就是:

  setlocal EnableDelayedExpansion设置var =旧值set var =新值&回声!var! 

这样,!var!值将被替换,直到执行 echo!var!命令(延迟扩展),并且在执行上一个 set 命令之后,因此先前的命令将显示:新值".

同一讨论适用于括号内 的任何变量.例如:

  set var =旧值如果1 == 1(设置var =新值回声%var%) 

...是错误的,因为在执行整个IF(或FOR)之前,只将%var%值扩展一次.您必须使用:

  setlocal EnableDelayedExpansion设置var =旧值如果1 == 1(设置var =新值回声!var!) 

输入 SET/?以获得更多详细信息.

Assignments (i.e. set statements) made within an if block are not realized until after the if block. So, in other words, you can't rely on variable assignment within an if block. How to fix this?

解决方案

Assignments in IF or FOR blocks are realized immediately. What is not properly realized is the sustitution of variable values enclosed in percent signs. You must note that a %variable% value is replaced before executing the line. For example:

set var=Old value
set var=New value & echo %var%

Previous commands show: "Old value". The way to solve this problem is via Delayed Expansion, that is, enclose the variable in exclamation marks instead percents and add a setlocal ... command at beginning. That is:

setlocal EnableDelayedExpansion
set var=Old value
set var=New value & echo !var!

This way, !var! value is replaced until echo !var! command is executed (delayed expansion) and after the previous set command is executed, so previous commands show: "New value".

This same dicussion apply to any variable inside parentheses. For example:

set var=Old value
if 1 == 1 (
   set var=New value
   echo %var%
)

...is wrong because %var% value is expanded just once before executing the whole IF (or FOR). You must use:

setlocal EnableDelayedExpansion
set var=Old value
if 1 == 1 (
   set var=New value
   echo !var!
)

Type SET /? for further details.

这篇关于如何在if块内实现赋值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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