0

I'm trying to compile a very simple command in a .bat file.

whoami > "Desktop/laptop.txt"

However, when I run it, cmd.exe interprets it as:

whoami 1> "Desktop/laptop.txt"

This is invalid due to the number 1 added before the >. The command does not run.

I can't find a way to get this number 1 to go away.

double-beep
  • 5,031
  • 17
  • 33
  • 41
Steven Tran
  • 26
  • 1
  • 7
  • 1
    `whoami 1>file.dat` works for me. `1>` is equivalent to `>` on its own, and redirects stdout. `2>` can be used to redirect stderr. – Joe Mar 23 '19 at 16:48
  • 3
    It is not invalid, but actually the correct usage. Using `>`, is simply a lazy way of using `1>` because StdOut, is the default for the redirection operator. You are actually only seeing the command which is being run. If it is not necessary to see the actual command being run, _(it rarely is)_, you could use `@WhoAmI > "Desktop\laptop.txt"` _(where prepending with `@` directly turns of its echoing)_. If you don't need to see any of this echoing you could, begin your batch file with an `@Echo Off` instruction to turn off all of this echoing, instead of prepending each individual command. – Compo Mar 23 '19 at 17:13

1 Answers1

1

To conclude what said in comments, the command line interpreter, interprets > (redirection character) and >> (append character) as 1> and 1>> respectively if they are alone, e.g. echo sth > filename or echo sth >> filename.

That is because the numeric handles are as follows:

  • 0 redirects/appends STDIN to somewhere specified.
  • 1 redirects/appends STDOUT to somewhere specified.
  • 2 redirects/appends STDERR to somewhere specified
  • 3-9 are undefined

So, when you type your command:

whoami > "Desktop/laptop.txt"

interpreter cannot understand it and automatically makes it 1> ... because it assumes you want to redirect STDOUT to Desktop/laptop.txt.

See some interesting links for further reading:

double-beep
  • 5,031
  • 17
  • 33
  • 41
  • *"interpreter cannot understand it **and automatically** makes it `1> ...`* - eh, I don't think I would say that. The interpreter understands just fine. I think it is more about showing the user how the parser is interpreting the the command by explicitly writing the handle as 1 (meaning stdout). – dbenham Mar 23 '19 at 20:28
  • When you start doing PowerShell, there are several more output streams. https://devblogs.microsoft.com/scripting/weekend-scripter-welcome-to-the-powershell-information-stream/ – lit Mar 23 '19 at 21:31