How do I echo and send console output to a file in a bat script?
Just use the Windows version of the UNIX tee command (found from http://unxutils.sourceforge.net) in this way:
mycommand > tee outpu_file.txt
If you also need the STDERR output, then use the following.
The 2>&1
combines the STDERR output into STDOUT (the primary stream).
mycommand 2>&1 | tee output_file.txt
No, you can't with pure redirection.
But with some tricks (like tee.bat) you can.
I try to explain the redirection a bit.
You redirect one of the ten streams with > file or < file
It is unimportant, if the redirection is before or after the command,
so these two lines are nearly the same.
dir > file.txt
> file.txt dir
The redirection in this example is only a shortcut for 1>, this means the stream 1 (STDOUT) will be redirected.
So you can redirect any stream with prepending the number like 2> err.txt and it is also allowed to redirect multiple streams in one line.
dir 1> files.txt 2> err.txt 3> nothing.txt
In this example the "standard output" will go into files.txt, all errors will be in err.txt and the stream3 will go into nothing.txt (DIR doesn't use the stream 3).
Stream0 is STDIN
Stream1 is STDOUT
Stream2 is STDERR
Stream3-9 are not used
But what happens if you try to redirect the same stream multiple times?
dir > files.txt > two.txt
"There can be only one", and it is always the last one!
So it is equal to dir > two.txt
Ok, there is one extra possibility, redirecting a stream to another stream.
dir 1>files.txt 2>&1
2>&1 redirects stream2 to stream1 and 1>files.txt redirects all to files.txt.
The order is important here!
dir ... 1>nul 2>&1
dir ... 2>&1 1>nul
are different. The first one redirects all (STDOUT and STDERR) to NUL,
but the second line redirects the STDOUT to NUL and STDERR to the "empty" STDOUT.
As one conclusion, it is obvious why the examples of Otávio Décio and andynormancx can't work.
command > file >&1
dir > file.txt >&2
Both try to redirect stream1 two times, but "There can be only one", and it's always the last one.
So you get
command 1>&1
dir 1>&2
And in the first sample redirecting of stream1 to stream1 is not allowed (and not very useful).
Hope it helps.