Search code examples
batch-filecmd

How to echo out a line ending in a "=0" into a file


Using the batch file generator.bat:

REM Test file creator
SETLOCAL

ECHO Test generated file! >>testfile.txt
ECHO assign var1=0>>testfile.txt
ECHO assign var1=1>>testfile.txt
ECHO assign var1=two>>testfile.txt
ECHO assigned var1>>testfile.txt

ENDLOCAL

I am able to generate the file: testfile.txt

Test generated file! 
assign var1=
assign var1=two
assigned var1

How can I add some sort of separator character so these lines are printed properly? The intended output file testfile.txt would be:

Test generated file! 
assign var1=0
assign var1=1
assign var1=two
assigned var1

Adding a space before the >> ie:

ECHO assign var1=0 >>testfile.txt

Simply results in the following:

assign var1=0 

Where the value is actually 0 (space added). This is an issue because I am using a similar generator to create another batch file, and the additional whitespace changes the meaning of the value.

  • Added spaces which changed the output values to have spaces appended
  • Tried to put the line into a variable and echo out the variable

Solution

  • You've got two options:

    you can either move the redirection to the front of the line

    >>testfile.txt ECHO assign var1=0
    >>testfile.txt ECHO assign var1=1
    

    or you can put everything in parentheses since you have multiple redirects going to the same file

    (
        ECHO Test generated file!
        ECHO assign var1=0
        ECHO assign var1=1
        ECHO assign var1=two
        ECHO assigned var1
    )>>testfile.txt