如何将控制台输出回显并发送到 bat 脚本中的文件?

问题描述:

我有一个执行任务并将输出发送到文本文件的批处理脚本.有没有办法让输出也显示在控制台窗口上?

I have a batch script that executes a task and sends the output to a text file. Is there a way to have the output show on the console window as well?

例如:

c:Windows>dir > windows-dir.txt

有没有办法让 dir 的输出显示在控制台窗口中并放入文本文件中?

Is there a way to have the output of dir display in the console window as well as put it into the text file?

不,您不能使用纯重定向.
但是通过一些技巧(例如 tee.bat),您可以.

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

本例中的重定向只是1>的快捷方式,这意味着流1(STDOUT)将被重定向.
因此,您可以重定向任何流,并在前面加上 2> 之类的数字.err.txt 并且还允许在一行中重定向多个流.

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

在这个例子中,标准输出"将进入 files.txt,所有错误都将在 err.txt 中,stream3 将进入 nothing.txt(DIR 不使用流 3).
Stream0 是标准输入
Stream1 是标准输出
Stream2 是 STDERR
Stream3-9 未使用

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

只有一个",而且永远是最后一个!
所以它等于 dir >二.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 将流 2 重定向到流 1,1>files.txt 将所有重定向到 files.txt.
顺序在这里很重要!

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

不一样.第一个将所有(STDOUT 和 STDERR)重定向到 NUL,
但第二行将 STDOUT 重定向到 NUL 并将 STDERR 重定向到空"标准输出.

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.

作为一个结论,很明显为什么 Otávio Décio 和 andynormancx 的例子不起作用.

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

两者都尝试重定向 stream1 两次,但只能有一个",而且总是最后一个.
所以你得到

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

并且在第一个示例中,不允许将流 1 重定向到流 1(并且不是很有用).

And in the first sample redirecting of stream1 to stream1 is not allowed (and not very useful).

希望有帮助.