user3688529
user3688529

Reputation: 97

Batch File: Output variable to text file

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!

UPDATE:

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!

Upvotes: 0

Views: 2190

Answers (2)

Kingzel
Kingzel

Reputation: 467

EnableDelayedExpansion causes Variables to be expanded in simple language it causes the system to treat the value of variable and not the variable name itself

Upvotes: 0

ths
ths

Reputation: 2942

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.

Upvotes: 2

Related Questions