批处理文件:将变量输出到文本文件 [英] Batch File: Output variable to text file

查看:81
本文介绍了批处理文件:将变量输出到文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将变量输出到文本文件.我已经在代码中完成了此操作,但是在if语句中有一个输出,提示我无法正常工作.

I would like to output a variable to a text file. I have done this in my code, but I have one output within an if statement that I can't get to work.

if not exist "%TuningLog%" (
    set Title=Tuning Parameters Saving Log
    set LogTitle=--------- %Title% ---------
    echo %LogTitle%>> "%TuningLog%"
)

它应该做的所有事情是首先检查日志文件的是否存在,如果不存在,那么我想在第一个实例中添加标题.

All its supposed to do is check first for the existense of a log file and if it doesn't exist then I want to in the first instance append a title.

但是我在日志文件中得到的只是回显已关闭".如果我不使用变量,而只在其中放置文本,那么它将正常工作.

But all I get in the log file is " echo is off." If I don't use a variable and just place text there then it works fine.

有人可以发现问题吗?感谢您的阅读和任何帮助!

Can anybody spot the problem? Thanks for reading and for any help!

更新:

我将代码更改为.我对延迟的扩展了解不多,但是我尝试了一下,但是它确实起作用了……

I changed my code to. I don't know much about delayed expansion, but I tried this and it happened to work...

if not exist "%TuningLog%" (
    setlocal enabledelayedexpansion
    set Title=Tuning Parameters Saving Log
    set LogTitle=--------- !Title! ---------
    echo !LogTitle!>> "!TuningLog!"
    endlocal
)

如果任何人都可以提供原因说明第一次尝试没有成功的原因,那么请为该线程通知以供学习.谢谢!

If anyone can provide a reason as to why the first attempt didn't work and this did, then please inform this thread for the purposes of learning. Thank you!

推荐答案

是因为还是早期的扩展.您的变量将在块开始时被其值替换.此时,它仍然是未定义的,因此为空.如果您有回声,则可以在屏幕上观看此情况.如果您启用了延迟扩展(如您在第二个示例中所做的那样),那么它只会在使用时立即扩展,因此它可以按您期望的变量在实际"编程语言中运行的方式工作.

because or early expansion. your variable gets replaced with its value at the moment the block starts. at this time, it is still undefined and thus empty. if you have echo on, you can watch this happening on screen. if you enable delayed expansion, as you did in your second example, it gets only expanded at the moment it is used, so it works as you expect variables to work in "real" programming languages.

这篇关于批处理文件:将变量输出到文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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