6

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!

FITZ
  • 63
  • 1
  • 1
  • 4

3 Answers3

6

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
merlin2011
  • 71,677
  • 44
  • 195
  • 329
5

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%
foxidrive
  • 40,353
  • 10
  • 53
  • 68
0

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
Bomba Ps
  • 109
  • 1
  • 4