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

Raymond Chen

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.

3 comments

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

  • 紅樓鍮 0

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

  • Martin Ba 0
    ..whatever..
    ⇑
    🤨

    I need to remember this pattern for Code Review 😀

    • 紅樓鍮 0

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

Feedback usabilla icon