FITZ
FITZ

Reputation: 63

How do I write the value of a variable to a dos text file?

How do I write a variable value to a text file within a dos batch script?

(Y, JJJ, SERL, and SERIAL are variables in the batch file)

I tried the following:

set SERIAL=%Y%+%JJJ%+%SERL% 
%SERIAL% > VAR_1.TXT
%T% > VAR_2.TXT
%A% > VAR_3.TXT
%SERL% > VAR_4.TXT

The files VAR_!.txt, VAR_2.txt, VAR_3.txt, VAR_4.txt are created, but they are empty (0 bytes).

I know this has a simple solution, but it has been 20+ years since I played with batch files (VERY rusty!)

THANKS!

Upvotes: 6

Views: 19568

Answers (3)

Bomba Ps
Bomba Ps

Reputation: 109

Please note, that variables can be hidden from global context if used inside SETLOCAL ENDLOCAL block.

Also If You want to append instead to create new file You can use >>

SETLOCAL 
CALL SET B="fiiLOCAL"
echo %A% > VAR_1.TXT
SET A="fooGLOB2"
echo %B% >> VAR_1.TXT
ENDLOCAL
TYPE var_1.txt

Upvotes: 0

foxidrive
foxidrive

Reputation: 41242

This method allows long filenames and also stops the trailing spaces from being included in the files (the spaces are to stop other problems, but this method is preferable).

The ( characters are a good practice to avoid another bug in echo.

>"VAR_1.TXT" echo(%SERIAL%
>"VAR_2.TXT" echo(%T%
>"VAR_3.TXT" echo(%A%
>"VAR_4.TXT" echo(%SERL%

Upvotes: 5

merlin2011
merlin2011

Reputation: 75585

Try using echo to get the value out?

echo %SERIAL% > VAR_1.TXT
echo %T% > VAR_2.TXT
echo %A% > VAR_3.TXT
echo %SERL% > VAR_4.TXT

Upvotes: 6

Related Questions