【问题标题】:Batch - How can I redirect stderr and stdout from within the batch script itself?批处理 - 如何从批处理脚本本身重定向标准错误和标准输出?
【发布时间】:2012-04-20 02:52:25
【问题描述】:

在 Unix shell 脚本中,可以从内部脚本本身重定向标准错误和标准输出,如下所示:

#!/bin/ksh
# script_name: test.sh
export AUTO_LOGFILE=`basename $0 .sh`.log
# stdout and stderr Redirection. This will save the old stdout on FD 3, and the old stderr on FD 4.
exec 3>&0 4>&1 >>$AUTO_LOGFILE 2>&1
echo "Hello World"
# The above echo will be printed to test.log

实际上,test.sh 可以简单地执行为:

test.sh

代替:

test.sh >> test.log 2>&1    

我正在尝试在批处理脚本中做类似的事情。我的批处理代码如下:

@echo off & setlocal enableextensions enabledelayedexpansion
REM script_name=test.bat
set AUTO_LOGFILE=%~n0.log
REM How to do the stdout and stderr redirection from within the script itself here?

如何从批处理脚本本身重定向标准错误和标准输出?我更感兴趣的是将这个 unix shell 脚本语句转换为等效的批处理代码:

exec 3>&0 4>&1 >>$AUTO_LOGFILE 2>&1

【问题讨论】:

  • 您的问题与此重复:[是否可以在脚本内重定向批处理文件的输出?][1] [1]:stackoverflow.com/questions/4607390/…
  • @Mac 我需要在脚本的后半部分执行许多命令并调用许多子例程。正如您提供的链接中的答案中提到的那样,我不能简单地在函数 testitout 中做到这一点。
  • 不确定,但如果你有一个子例程,就像你的 main 调用其他子例程一样,那不行吗?
  • @MAC 嗯...会调查的。但我更感兴趣的是将此 unix shell 脚本语句转换为等效的批处理代码: exec 3>&0 4>&1 >>$AUTO_LOGFILE 2>&1
  • 我认为 0 是标准输入、1 标准输出和 2 标准错误。那么你的 exec 行不应该是 exec 3>&1 4>&2 >>$AUTO_LOGFILE 2>&1 吗?

标签: batch-file


【解决方案1】:

下面的test.bat批处理文件功能等同到您的Unix脚本,也就是说,它将所有标准输出发送到日志文件并将错误输出发送到屏幕:

@echo off
if defined reEntry goto reEntry
set reEntry=TRUE

set AUTO_LOGFILE=%~N0.log
rem stdout Redirection. Leave stderr as is.

"%~F0" %* >>%AUTO_LOGFILE%

:reEntry
set reEntry=
echo "Hello World"
rem The above echo will be printed to test.log
rem and error messages will be printed to the screen:
verify badparam

附录:

我认为 OP 想要将标准输出与标准错误分开以在屏幕上查看错误消息,但也许我误解了他。要将 stdout 和 stderr 都发送到文件,请使用下面的行,如 dbenham 在他的评论中指出的那样:

"%~F0" %* >>%AUTO_LOGFILE% 2>&1

或者以上面评论中已经建议的更简单的方式:

@echo off
set AUTO_LOGFILE=%~N0.log
rem stdout and stderr Redirection.

call :Main %* >>%AUTO_LOGFILE% 2>&1
goto :EOF

:Main
echo "Hello World"
rem The above echo will be printed to test.log

但是,如果目的是区分错误消息与正常输出,则可以通过以下技巧在同一屏幕上完成:

"%~F0" %* 2>&1 1>&3 | findstr /N /A:4E "^"

这样,错误消息前面会出现一个红色背景上的黄色行号。这种方法可以在几种情况下直接使用;例如,在任何编程语言源程序的编译中:

anycompiler %1 2>&1 1>&3 | findstr /N /A:4E "^"

【讨论】:

  • +1 但是,我认为 OP 想要将 stderr 重定向到同一个文件,所以 "%~F0" %* >>%AUTO_LOGFILE% 2>&1。此外,Windows 会自动将重定向句柄保存到第一个可用的未分配句柄。因此,除非发生了先前的重定向,否则原始 stdout 将保存在句柄 3 中,而 stderr 保存在句柄 4 中。所以echo This will go to the console (stdout) >&3 会这样做。
【解决方案2】:

用括号括起来

(
  REM How to do the stdout redirection from within the script itself here?
  ECHO is this redirected?
  ECHO yes it is
) >out.txt

【讨论】:

    猜你喜欢
    • 2012-11-04
    • 1970-01-01
    • 2010-10-29
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多