Search code examples
windowsbatch-filecmddos

Unexpected command line behavior using commas in Windows/DOS batch file


Today, I wanted to test if filenames can contain commas and stumbled upon something else while opening cmd and trying these three tests:

echo a,b>a

This works as supposed (writes a,b to the file named a)

echo a>a,b

Does just the same! What happens here gets a bit clearer with the third test:

echo a>file,b this is a test

This will create a file named file containing a,b this is a test.

Now, three questions arise for me:

  1. What is the explanation for this? If someone asked me, I would've guessed the comma separates commands or filenames, e.g. I would've expected the second test to create two files named a and b.
  2. Is this behaviour documented somewhere?
  3. Is it a cmd specific Windows extension or has it been like this since good old DOS times?

Solution

  • It's expected behaviour as ,;=<space><tab> are delimiters for parameters.
    If you put the code into a batch file without echo OFF you will see

    test.bat

    echo a,b>a
    echo a>a,b
    echo a>file,b this is a test
    

    Output

    C:\temp>test.bat
    C:\temp>echo a,b 1>a
    C:\temp>echo a,b 1>a
    C:\temp>echo a,b this is a test 1>file
    

    After a redirection, only the next token is relevant, the rest is part of the normal line content.
    It's unimportant where the redirection occurs in a line.
    But there is the rule that when more than one redirection exists for the same stream, the last one will win.

    > file.txt echo hello> nul world > con
    

    This will result in hello world at the console.

    Btw. There is still an obscure behaviour with redirection and lines extended by carets (multilines).

    echo one two three^
     four
    

    Result: one two three four

    But

    echo one two >con three^
     four
    

    Result: one two four