批处理文件未能设置条件语句中的环境变量 [英] Batch file fails to set environment variable within conditional statement

查看:192
本文介绍了批处理文件未能设置条件语句中的环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的Windows批处理文件输出 followedby 酒吧,而不是巴兹

 关闭@echo
SETLOCAL设置_ =富
回声%_%
设置_ =酒吧
如果1 == 1(
    设置_ =巴兹
    回声%_%

我的系统上的输出(微软的Windows XP [版本5.1.2600])是:

 
酒吧

如果我删除了条件语句,预期输出巴兹观察。


解决方案

这是怎么回事的是,当读取行变量替换完成。什么你没有考虑到的事实是:

 如果1 == 1(
    设置_ =巴兹
    回声%_%

有一个的线,尽管你可能认为。的%_%完成的的的设置语句

您需要的是延迟扩展。只是我的命令脚本每一个人与SETLOCAL ENABLEEXTENSIONS enabledelayedexpansion,以便使用的全功率的cmd.exe

所以我的剧本的版本是:

 关闭@echo
SETLOCAL ENABLEEXTENSIONS enabledelayedexpansion设置_ =富
回音!_!
设置_ =酒吧
如果1 == 1(
    设置_ =巴兹
    回音!_!
)ENDLOCAL

这生成正确的富,巴兹,而不是富,酒吧

Why does the following Windows Batch File output Foo followedby Bar, rather than Baz?

@echo off
setlocal

set _=Foo
echo %_%
set _=Bar
if 1==1 (
    set _=Baz
    echo %_%
)

The output on my system (Microsoft Windows XP [Version 5.1.2600]) is:

Foo
Bar

If I remove the conditional statement, the expected output of Foo and Baz is observed.

解决方案

What's happening is that variable substitution is done when a line is read. What you're failing to take into account is the fact that:

if 1==1 (
    set _=Baz
    echo %_%
)

is one "line", despite what you may think. The expansion of "%_%" is done before the set statement.

What you need is delayed expansion. Just about every single one of my command scripts starts with "setlocal enableextensions enabledelayedexpansion" so as to use the full power of cmd.exe.

So my version of the script would be:

@echo off
setlocal enableextensions enabledelayedexpansion

set _=Foo
echo !_!
set _=Bar
if 1==1 (
    set _=Baz
    echo !_!
)

endlocal

This generates the correct "Foo", "Baz" rather than "Foo", "Bar".

这篇关于批处理文件未能设置条件语句中的环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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