batch-filecmdwindows-10

cmd batch execution adds a space after echo


When I run a script, for example one that says

echo a>>1.txt

the command line interpreter adds a space; so in the command line, executing the above says

echo a  1>> 1.txt

And of course, the end of the line gets a space, which I do not need.

So then I thought, I will put the echo in parentheses. So my batch file became:

(echo a)>>1.txt

However, the command prompt did not give up with the space. It now says:

(echo a ) 1>> 1.txt

How to get rid of the space? I even tried modifying my file to say

>>1.txt (echo a)

However, the command prompt still re-formats it, and displays the same command as above on the command prompt, and I cannot get rid of the space.

Just for clarification. This question has now been associated with another question, saying it is a duplicate. It is not. The solution in the other question was to use a parenthesis in order to prevent the space from being auto-added. In my question, I already used parentheses in my query.

In this case, the space was coming from the redirection, and the comment to add cmd.exe /c worked to solve my issue.


Solution

  • Your assumption is wrong, the file does not contain a space.
    The ECHO ON mode shows (echo a ) 1>out.txt, but it does not execute it with a space.
    The resulting file has exactly 3 characters as expected (one "a" and CR/LF)

    mytest.bat

    @echo off
    setlocal
    set "prompt=#DEBUG# "
    echo ON
    (echo a)>out.txt
    
    @echo off
    dir out.txt
    
    

    Output:

    
    #DEBUG# (echo a ) 1>out.txt
     Datenträger in Laufwerk Z: ist VBOX_batch
     Volumeseriennummer: 0001-0305
    
     Verzeichnis von Z:\bat
    
    06/17/2025  07:35 PM                 3 out.txt
                   1 Datei(en),              3 Bytes