November 16th, 2020

Why does my command line redirection echo with an extra 1? Who’s inserting these rogue 1s everywhere?

If you leave echo enabled in your batch file, and the batch file executes a command with redirection, then a mysterious 1 is inserted.

C:\> copy con %TEMP%\test.cmd
dir >nul
^Z
        1 file(s) copied.

C:\> %TEMP%\test.cmd

C:\> dir  1>nul
          
          🤨

The rogue 1 appears to be a purely visual glitch. There is no actual 1 inserted into the command line. In this example, the directory listing is of the current directory, not of a directory named 1.

Where is this 1 coming from?

Recall that digits before the redirection operator specify the stream being redirected. (This is one of the reasons why I have a habit of putting the redirection at the start of the command line.)

By default, if there is no stream specified, then the stream that is redirected is stdout, and stdout‘s stream number is… 1.

Okay, the pieces are starting to come together.

If echo is enabled, then the command processor prints each command before executing it. But this happens after the command line is parsed, and part of parsing the redirection operator is remembering which stream is being redirected. The command processor regenerates the original command line from what it had parsed, and when it sees that the parsed redirection operator, it dutifully puts the stream number in front.

If you didn’t specify an explicit stream to redirect, then the default stream (stdout = 1) is printed, because that is in fact what stream is being redirected.

It’s just a quirk. The functionality is unaffected. Though it does look a little weird the first time you notice it.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

3 comments

Discussion is closed. Login to edit/delete existing comments.

  • Martin Ba
    ..whatever..
    ⇑
    🤨

    I need to remember this pattern for Code Review 😀

    • 紅樓鍮

      We should persuade our favorite compilers to generate emoji for error messages.

  • 紅樓鍮

    Truth be told this is the first time I see an emoji typed by Raymond